【发布时间】:2010-11-06 15:53:20
【问题描述】:
如果当迭代器指向向量的最后一个元素时,我将迭代器增加 2 会怎样?在 this question 询问如何通过 2 个元素将迭代器调整为 STL 容器时,提供了两种不同的方法:
- 使用算术运算符的一种形式 - +=2 或 ++ 两次
- 或使用 std::advance()
当迭代器指向 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
我见过多次建议在遍历向量和其他容器时与 vector::end() 进行比较:
for( vector<int>::iterator it = vec.begin(); it != vec.end(); it++ ) {
//manipulate the element through the iterator here
}
显然,如果迭代器超过循环内的最后一个元素,则 for 循环语句中的比较将评估为 false,并且循环将愉快地继续进行未定义的行为。
如果我曾经在迭代器上使用Advance() 或任何类型的增量操作并使其指向容器的末端,我是否正确,我将无法检测到这种情况?如果是这样,最佳做法是什么 - 不使用此类改进?
【问题讨论】: