[英]Why does this vector iterator not become invalidated?
I've read a few posts concerning iterator invalidation, and it seems that inserts that require a vector reallocation would invalidate iterators. 我读过一些有关迭代器失效的文章,似乎要求向量重新分配的插入会使迭代器失效。 Also shouldn't erases in the middle of the vector cause an invalidation?
同样不应该在向量中间擦除导致无效吗?
I don't have a clear understanding of this, not sure why using these iterators after resizes and erases from begin, middle, and end doesn't break them: 我对此没有一个清晰的了解,不知道为什么在从开始,中间和结束调整大小和擦除之后使用这些迭代器不会破坏它们:
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
vector<int> v;
v.reserve(10);
for (int i = 0; i < 10; i++)
v.push_back(i);
for (auto x = v.begin(); x != v.end(); x++) {
cout << *x << endl;
}
cout << endl << "RESIZE" << endl << endl;
for (int i = 10; i < 20; i++)
v.push_back(i);
for (auto x = v.begin(); x != v.end(); x++) {
cout << *x << endl;
}
cout << endl << "RESIZE 2" << endl << endl;
for (int i = 20; i < 200; i++)
v.push_back(i);
for (auto x = v.begin(); x != v.end(); x++) {
cout << *x << endl;
}
cout << endl << "REMOVES" << endl << endl;
v.erase(v.begin());
v.pop_back();
v.erase(v.begin() + 17);
for (auto x = v.begin(); x != v.end(); x++) {
cout << *x << endl;
}
return 0;
}
Note that calling begin() or end() will always provide a sane iterator 请注意,调用begin()或end()将始终提供合理的迭代器
However something like: 但是类似:
std:vector<int> v;
....
std::vector<int>::iterator i=v.begin();
v.erase(i);
std::cout << *i << std::endl; // i iterator was invalidated by erasing it
// trying to access it or increment it is undefined behaviour.
std::cout << *v.begin() << std::endl; // begin() provides always a sane iterator.
In your code, always when iterators are reused, there was no intervening modification of the vector, so no invalidation. 在您的代码中,总是在重复使用迭代器时,不会对向量进行中间修改,因此也不会导致无效。
Iterators may be invalidated on resizing and inserting. 调整大小和插入时,迭代器可能会失效。 Erasing only invalidates iterators at or after the erased element.
擦除仅会使被擦除元素处或之后的迭代器无效。
At least, those are the paraphrased rules for std::vector
. 至少,这些是
std::vector
的释义规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.