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/