c++ - 如果迭代器在 STL 容器中失效,指针是否失效

标签 c++ pointers stl iterator

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

    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 容器来说,如果迭代器失效,那么指针也会失效,这样说是否安全?例如,如果 it 变得无效,那么 ptr 也会无效吗?如果不能,您能否给出一个迭代器失效但指针仍然有效的情况?我目前对 vectors 、 maps 和 deques 感兴趣。

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

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

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

最佳答案

当您移除一个项目时,不同的容器会有不同的行为。

来自 http://en.cppreference.com :

std::vector::erase

Invalidates iterators and references at or after the point of the erase, including the end() iterator.

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.

关于c++ - 如果迭代器在 STL 容器中失效,指针是否失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793784/

相关文章:

c++ - 从 stdout 读取奇怪的性能问题

c++ - 为什么在C++中这个double值乘以2会出现计算错误?

c++ - 带有MinGW STL的Clang(错误: no member named 'fgetws' in the global namespace)

c - 在 C 函数中初始化结构指针

c++ - 如果数组很大,使用指针作为 C++ 类成员是否是一种更有效的方法?

c++ - vs2015 上的 STL 列表性能不佳,同时删除包含指向自身在列表中位置的迭代器的节点

c++ - STL Set inside Map ,奇怪的段错误和Valgrind分析

c++ - 加、减和比较压缩整数

c++ - Qt:禁用按钮而不将其变成灰色

iphone - 为什么执行选择器:withObject: methods can only take id?