如果我将一个迭代器增加2当它指向一个向量的最后一个元素怎么办? [英] What if I increment an iterator by 2 when it points onto the last element of a vector?

查看:224
本文介绍了如果我将一个迭代器增加2当它指向一个向量的最后一个元素怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题中,询问如何将迭代器调整为STL容器由2个元素提供两种不同的方法:

In this question asking how to adjust the iterator to an STL container by 2 elements two different approaches are offered:


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

  • 或使用std :: advance()

对于边缘情况,当迭代器指向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-loop语句中的比较将计算为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的书: / p>

Following is the quote from Nicolai Josuttis book:


请注意,advance()不检查
是否跨越
序列的末尾't检查,因为
迭代器一般不知道他们操作的
容器)。
因此,调用此函数可能
导致未定义的行为,因为
未定义
序列结束时调用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.

这篇关于如果我将一个迭代器增加2当它指向一个向量的最后一个元素怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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