如果增加一个等于STL容器的结束迭代器的迭代器,会发生什么 [英] What happens if you increment an iterator that is equal to the end iterator of an STL container

查看:162
本文介绍了如果增加一个等于STL容器的结束迭代器的迭代器,会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当迭代器指向向量的最后一个元素时,如果将迭代器增加2,该怎么办?在这个问题中询问如何通过以下方式调整迭代器到STL容器2个元素提供了两种不同的方法:

What if I increment an iterator by 2 when it points onto the last element of a vector? In this question asking how to adjust the iterator to an STL container by 2 elements two different approaches are offered:


  • 使用算术运算符的形式 - + = 2或++两次

  • 或者使用std :: advance()

我用VC ++ 7测试了它们的两个边缘迭代器指向STL容器的最后一个元素或更高的情况:

I've tested both of them with VC++ 7 for the edge case when the iterator points onto the last element of the STL container or beyond:

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()时遍历向量和其他容器:

I've seen may times an advise to compare against vector::end() when traversing the vector and other containers:

for( vector<int>::iterator it = vec.begin(); it != vec.end(); it++ ) {
    //manipulate the element through the iterator here
}

显然,如果迭代器超出循环内的最后一个元素,则for循环语句中的比较将计算为false,并且循环将很快继续进入未定义的行为。

Obviously if the iterator is advanced past the last element inside the loop the comparison in the for-loop statement will evaluate to false and the loop will happily continue into undefined behaviour.

我是否认为如果我在迭代器上使用advance()或任何类型的递增操作并使其指向容器的末尾,我将无法检测到这种情况?如果是这样,最佳做法是什么 - 不使用这些进步?

Do I get it right that if I ever use advance() or any kind of increment operation on an iterator and make it point past the container's end I will be unable to detect this situation? If so, what is the best practice - not to use such advancements?

推荐答案

以下是Nicolai Josuttis的书:

Following is the quote from Nicolai Josuttis book:


请注意,advance()不会检查
它是否越过
序列的end()(它可以检查是因为
迭代器通常不知道它们运行的​​
容器。
因此,调用此函数可能会导致
导致未定义的行为,因为
调用operator ++作为
序列的末尾未定义

Note that advance() does not check whether it crosses the end() of a sequence (it can't check because iterators in general do not know the containers on which they operate). Thus, calling this function might result in undefined behavior because calling operator ++ for the end of a sequence is not defined

换句话说,在范围内维护迭代器的责任完全在于调用者。

In other words, the responsibility of maintaining the iterator within the range lies totally with the caller.

这篇关于如果增加一个等于STL容器的结束迭代器的迭代器,会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆