如果我将迭代器指向向量的最后一个元素时,它会增加2怎么办?在这个询问如何通过2个元素调整到STL容器的迭代器的问题中,提供了两种不同的方法:
当迭代器指向STL容器的最后一个元素或更远时,我用VC++ 7测试了它们的边缘情况:
vector<int> vec;
vec.push_back( 1 );
vec.push_back( 2 );
vector<int>::iterator it = vec.begin();
advance( it, 2 );
bool isAtEnd = it == vec.end(); // true
it++; // or advance( it, 1 ); - doesn't matter
isAtEnd = it == vec.end(); //false
it = vec.begin();
advance( it, 3 );
isAtEnd = it == vec.end(); // false
Run Code Online (Sandbox Code Playgroud)
我已经看过有时可以建议在遍历vector和其他容器时与vector :: end()进行比较:
for( vector<int>::iterator it = vec.begin(); it != vec.end(); …Run Code Online (Sandbox Code Playgroud) 在经历了一些痛苦之后,我设法将这个最小的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