为什么boost filter_iterator有奇怪的make_filter_iterator函数
Why boost filter_iterator has weird make_filter_iterator function?
经过一番努力,我设法拼凑了这个最小的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()
迭代器
相关文章:
- Visual Studio C++ Project File CustomBuild Task: Filter Outp
- 在调试模式下引发C++ "deque iterator not dereferencable"异常
- std::iterator::reference 必须是引用吗?
- C++,调用'filter'没有匹配功能
- 如何使用虚幻引擎"filter"多播?
- 为什么unordered_set<string::iterator>不起作用?
- 造成致命错误:boost/fusion/iterator/equal_to.hpp 没有这样的文件或目录
- Visual accept std::string from std::byte iterator
- 什么是"std::set<int,int>::iterator"?
- 从 std::vector 中删除项目时"Iterator not incrementable"
- 如何从 boost::container::vector<std::string>::iterator 访问索引和对象?
- boost zlib filter 在 Windows 中不起作用
- 空集"Out of bound iterator"
- 如何使用set<pair<int,int> >::iterator itrator it迭代set<pair<int,int> >st中的值?
- 给定一个类型为 Container:<T>:Iterator 的函数参数,如何为某些类型的 T 实现特定的重载?
- sclite (SCTK),C++模板参数 Filter::Filter* 无效.西格温
- 带升压async_read_some "String iterator not dereferncable"
- C++为什么"deque iterator not dereferencable "
- 错误:与'operator='不匹配(操作数类型为"std::map<int、double>::iterator
- 自动,错误:MAP ITERATOR没有名为“ First”的成员