如果增加一个等于 STL 容器的结束迭代器的迭代器会发生什么

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

本文介绍了如果增加一个等于 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()

当迭代器指向 STL 容器的最后一个元素或其他元素时,我已经使用 VC++ 7 对它们进行了测试:

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 和其他容器时,我可能多次看到建议与 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 书中的引述:

Following is the quote from Nicolai Josuttis book:

注意advance() 不检查是否越过 a 的 end()序列(它无法检查,因为迭代器一般不知道他们操作的容器).因此,调用这个函数可能导致未定义的行为,因为在 a 的末尾调用运算符 ++序列未定义

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 容器的结束迭代器的迭代器会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如果增加一个等于 STL 容器的结束迭代器的迭代器会发生什么

基础教程推荐