MST

星途 面试题库

面试题:Rust迭代器适配器的自定义与性能优化

假设你有一个非常大的包含字符串的迭代器,你需要自定义一个适配器,它能够过滤掉长度小于5的字符串,同时要考虑到性能优化,避免不必要的内存分配和拷贝。请实现这个自定义适配器,并解释你的性能优化思路。
13.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试

实现代码(以C++为例)

#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>

// 自定义适配器类
class StringFilterAdapter {
private:
    std::istream_iterator<std::string> it;
    std::istream_iterator<std::string> end;
public:
    StringFilterAdapter(std::istream& stream) : it(stream), end() {}

    std::string operator*() const {
        while (it != end && (*it).size() < 5) {
            ++it;
        }
        return *it;
    }

    StringFilterAdapter& operator++() {
        do {
            ++it;
        } while (it != end && (*it).size() < 5);
        return *this;
    }

    bool operator!=(const StringFilterAdapter& other) const {
        return it != other.it;
    }
};

性能优化思路

  1. 延迟过滤:在operator*operator++中,只有在真正需要获取字符串或者移动到下一个字符串时才进行长度检查和过滤,避免提前对所有字符串进行不必要的检查。
  2. 避免拷贝:使用std::istream_iterator直接从输入流中读取字符串,避免在适配器内部进行额外的字符串拷贝。在过滤过程中,只是移动迭代器位置,不进行数据的拷贝操作,只有在最终获取到符合条件的字符串时才返回,减少了内存的分配和拷贝次数。

使用示例

int main() {
    std::vector<std::string> input = {"abc", "defgh", "ij", "klmno", "pqrs"};
    std::istringstream iss;
    for (const auto& str : input) {
        iss << str << " ";
    }
    iss.seekg(0);

    StringFilterAdapter start(iss);
    StringFilterAdapter end;

    std::vector<std::string> result;
    std::copy(start, end, std::back_inserter(result));

    for (const auto& str : result) {
        std::cout << str << " ";
    }
    std::cout << std::endl;

    return 0;
}

在这个示例中,StringFilterAdapter通过包装std::istream_iterator实现了对输入字符串的延迟过滤,从而提高了性能并减少了不必要的内存操作。