问题描述
我试图理解向量中迭代器失效的概念。
从我所做的一些阅读中我发现,如果一个向量包含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.
来自:
这篇关于如果迭代器在STL容器中失效,指针是否会失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!