如果迭代器在STL容器中失效,指针是否会失效 [英] Does a pointer become invalidated if an iterator is invalidated in STL containers

查看:201
本文介绍了如果迭代器在STL容器中失效,指针是否会失效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解向量中迭代器失效的概念。
从我所做的一些阅读中我发现,如果一个向量包含7个元素并删除第5个索引上的元素,那么从第5个元素开始的迭代器就会失效。这是因为第5个索引之后的所有元素都需要向上移动一个槽。这对我有意义但是我在以下两种情况之间有点困惑

I am trying to understand the concept of iterator invalidation in vectors. From some of the reading I have done I have found that if a vector contains say 7 elements and you delete the element on the 5th index then the iterators from 5th element onwards become invalidated. This is because all the elements after the 5th index would need to move up one slot. This makes sense to me however I am a bit confused between the following two cases

    std::vector<foo> vec {foo{1},foo{2}};              //foo is a simple class
    foo* ptr = &vec[0];                                //Case 1
    std::vector<foo>::iterator it = vec.begin() + 1;   //Case 2

如果迭代器失效,对于STL容器是否安全可行指针也变得无效?例如,如果失效, ptr 也会无效?如果没有,你能否给出迭代器失效但指针仍然有效的情况?我目前对矢量,地图和deques感兴趣。

Is it safe to say that for a STL container if an iterator becomes invalidated then a pointer becomes invalidated too ? For instance if it becomes invalidated will ptr be invalid too ? If not could you give a case in which an iterator becomes invalidated but a pointer remains valid ? I am currently interested in vectors , maps and deques.

更新:
所以我写了一些代码并进行了实验

Update: So I wrote a little code and experimented

std::vector<foo> vec {foo{1},foo{2},foo{3}};
foo* ptr = &vec[1];
std::vector<foo>::iterator it = vec.begin() + 1;
std::cout << "Before : " <<  ptr->a << "\n";
vec.erase(vec.begin() + 1); //Remove the second element
std::cout << "Iterator value : " << it->a << "\n";
std::cout << "After : " <<  ptr->a << "\n";

结果是

Before : 2
Iterator value : 3
After : 3

我很惊讶为什么向量没有提到迭代器是无效的,因为这是在删除元素之前获得的迭代器。

I am surprised why the vector did not mention that the iterator was invalid since this was the iterator obtained before an element was removed.

推荐答案

删除项目时,不同容器的行为会有所不同。

Different containers behave differently when you remove an item.

来自 http://en.cppreference.com

std :: vector :: erase


在擦除点或之后使迭代器和引用无效,包括 end()迭代器。

std :: map :: erase


擦除元素的引用和迭代器无效。其他引用和迭代器不受影响。

References and iterators to the erased elements are invalidated. Other references and iterators are not affected.

std :: deque :: erase


除非擦除的元素位于容器的末尾或开头,否则所有迭代器和引用都将失效,在这种情况下,只有迭代器和对擦除元素的引用才会失效。

All iterators and references are invalidated, unless the erased elements are at the end or the beginning of the container, in which case only the iterators and references to the erased elements are invalidated.

这篇关于如果迭代器在STL容器中失效,指针是否会失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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