【发布时间】:2020-01-10 00:08:49
【问题描述】:
如何确保迭代器不会超出向量范围?并且在过滤器不匹配输入的任何元素的情况下;在那种情况下,我如何确保 begin() 等于 end() 代码
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; }
};
struct FilteringIterator : Iterator {
Callable callable;
using OriginalIterator = Iterator;
Iterator end;
Iterator current=(Iterator &)*this;;
FilteringIterator(const Iterator begin, Iterator end, Callable callable):Iterator(begin),end(end),callable(callable){}
Iterator &get_orig_iter() { return ((Iterator &)*this); }
auto operator++(){ return ((Iterator &)*this)++;}
bool operator==(const Iterator& rhs) const { return ((Iterator &)*this) == rhs; }
bool operator!=(const Iterator& rhs) const { return !(operator==(rhs)); }
auto operator*() {
while ((Iterator &)*this!=end && !callable(*get_orig_iter()))
++(Iterator &)*this;
return *(Iterator &)*this;
}
};
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>;
auto t=filter_iterator{container.end(),container.end(),action};
return Range{filter_iterator{container.begin(),container.end(),action}, filter_iterator{container.end(),container.end(),action}};
};
};
主要
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
for(auto a : v | filter(less_then(15))) // filter is applied lazily as the range is traversed
std::cout << a <<"D" << std::endl;
// prints 17.5 and 22.5 to the console
输出
2.5
7.5
12.5
【问题讨论】:
-
将您的 while 循环移至 operator++。您的构造函数还应该寻找第一个满足您条件的迭代器。
-
你不应该在 C++ 代码中使用 C 风格转换!请改用
static_cast。更好的是使用组合来代替。许多这些演员都是无用的。OriginalIterator别名似乎没用。也许您应该考虑改用范围库(boost、C++ 20...)。 -
我明白我做错了什么,这是一个菜鸟的错误。将 while 循环移动到
operator!=并进行了一些修改,它就像一个魅力。谢谢。
标签: c++ iterator iteration runtime-error