NoS*_*tAl 4 c++ boost boost-iterators
在经历了一些痛苦之后,我设法将这个最小的boost filter_iterator示例整合在一起
using namespace std;
std::function<bool(uint32_t)> stlfunc= [](uint32_t n){return n%3==0;};
int main()
{
vector<uint32_t> numbers{11,22,33,44,55,66,77,3,6,9};
auto start = boost::make_filter_iterator(stlfunc, numbers.begin(), numbers.end());
auto end = boost::make_filter_iterator(stlfunc, numbers.end() , numbers.end());
auto elem = std::max_element(start,end);
cout << *elem;
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但我想知道为什么make_filter_iterator需要numbers.end()?我可能是错用这种方式,我guestimated它从C数组例如:
http://www.boost.org/doc/libs/1_53_0/libs/iterator/example/filter_iterator_example.cpp
这在文档中解释:
跳过元素时,过滤器适配器必须知道何时停止,以避免超过基础范围的末尾.因此,过滤器迭代器由一对迭代器构成,这些迭代器指示要遍历的未过滤序列中的元素范围.
从下面的源代码中,您可以看到始终检查它们是否已到达最终satisfy_predicate:
void increment()
{
++(this->base_reference());
satisfy_predicate();
}
void satisfy_predicate()
{
while (this->base() != this->m_end && !this->m_predicate(*this->base()))
++(this->base_reference());
}
Run Code Online (Sandbox Code Playgroud)
另外,正如Alex Chamberlain所指出的,构造函数在传递end迭代器时使它成为可选的,例如:( filter_iterator(Iterator x, Iterator end = Iterator());假设它是默认的可构造的).因此,numbers.end()在构造结束迭代器时,可以省略代码.