为什么boost filter_iterator有奇怪的make_filter_iterator函数

Why boost filter_iterator has weird make_filter_iterator function?

本文关键字:iterator filter make 函数 boost 为什么      更新时间:2023-10-16

经过一番努力,我设法拼凑了这个最小的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;
}

它工作得很好,但我想知道为什么make_filter_iterator需要numbers.end() ?我这样使用它可能是错误的,我从C数组的例子中估计了它:
http://www.boost.org/doc/libs/1_53_0/libs/iterator/example/filter_iterator_example.cpp

这在文档中有解释:

当跳过元素时,过滤器适配器必须知道什么时候停止,以避免越过潜在的终点的范围内。因此,用pair of构造过滤器迭代器指示未过滤序列中元素范围的迭代器要遍历。

从下面的源代码中,您可以看到always检查它们是否已到达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());
}

同样,正如Alex Chamberlain所指出的那样构造函数在传递结束迭代器时使其成为可选的,例如:filter_iterator(Iterator x, Iterator end = Iterator());(前提是它是默认可构造的)。因此,在构造结束迭代器时,可以从代码中省略numbers.end()

如果您查看make_filter_iterator模板的声明,您会看到它是这样的:

template <class Predicate, class Iterator>
filter_iterator<Predicate,Iterator>
make_filter_iterator(Predicate f, Iterator x, Iterator end = Iterator());

具体来说,你可以看到最后一个参数是默认参数,它被设置为Iterator(),这意味着它是默认构造的,对于的某些类型的迭代器,它的行为类似于实际的end()迭代器,它指向任何数组末尾的后面一个,即指向垃圾。

大多数容器类型确实需要传递一个实际的end()迭代器