c++ - 使用惰性迭代器进行C++过滤

标签 c++ iterator

template<typename Iterator>
    struct Range {
        using LazyIterator = Iterator; // required for accessing the used Iterator type from other locations
        Iterator m_begin;
        Iterator m_end;
        auto begin() { return m_begin; }
        auto end() { return m_end; }
    };

    template<typename Iterator>
    Range(Iterator, Iterator) -> Range<Iterator>;    
 template<typename Iterator, typename Callable>
        struct FilteringIterator : Iterator {
            Callable callable;
            using OriginalIterator = Iterator;
            using t = typename OriginalIterator::value_type;
            FilteringIterator(const Iterator begin, Callable callable):Iterator(begin),callable(callable){}
            Iterator &get_orig_iter() { return ((Iterator &)*this); }
            auto operator*() { return callable(*get_orig_iter()); }
        };
auto filter = [](auto action) {
    return [=]( auto &container) {
        using Container = std::decay_t<decltype(container)>;
        using Iterator = typename Container::iterator;
        using actiontype = decltype(action);
        using filter_iterator = FilteringIterator<Iterator, actiontype>;
        return Range{filter_iterator{container.begin(),action}, filter_iterator{container.end(),action}};
    };
};

我需要一个惰性迭代器,该迭代器将遍历一个范围并对其进行延迟过滤。
例如
auto v = std::vector<double>{};
    auto odd_gen = views::odds();

    for(int i=0; i<5; ++i)
        v.push_back(odd_gen() * 2.5);
    // v contains {2.5, 7.5, 12.5, 17.5, 22.5} here

    new_line();
    for(auto a : v | filter(greater_than(15))) // filter is applied lazily as the range is traversed
        std::cout << a  << std::endl;
// print { 17.5, 22.5} here

但它打印

{0,0,0,0,17.5,22.5}

我希望它只打印17.5、22.5

我该如何实现?

最佳答案

您的代码从不跳过元素,而只是对其进行转换。您需要确保在调用operator*()时,首先进行迭代,而callable返回false,然后仅返回Iterator指向的值。

有一些极端的情况,尽管您必须要照顾。如果输入的结尾元素与过滤器不匹配,则会遇到问题。当调用operator++()时,您还需要跳过所有过滤出的元素。再考虑一下过滤器不匹配输入中任何元素的情况;在这种情况下,必须确保begin()等于end()

关于c++ - 使用惰性迭代器进行C++过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59670343/

相关文章:

c++ - 使用不同的类类型重复 Boost 单元测试

c++ - 为什么 STD vector 在分配时不调用默认构造函数?

c++ - 代码在 Visual Studio 中编译良好,但在使用 g++ 的 Unix 终端中编译不佳。我在多维 vector 处出错。为什么?

c++异常访问冲突与int变量

c++ - 为什么 const_iterator 不像 reverse_iterator 那样提供基类?

c++ - 如何在 C++ 中管理大缓冲区?

c++ - 获取 std::vector 的迭代器的更短方法

c++ - 更新元素 STL 列表列表

c++ - std::map 迭代器如何工作?

java - 如何同时打印和删除迭代器中的元素?