![](/img/trans.png)
[英]Does a pointer become invalidated if an iterator is invalidated in STL containers
[英]Why does this vector iterator not become invalidated?
我读过一些有关迭代器失效的文章,似乎要求向量重新分配的插入会使迭代器失效。 同样不应该在向量中间擦除导致无效吗?
我对此没有一个清晰的了解,不知道为什么在从开始,中间和结束调整大小和擦除之后使用这些迭代器不会破坏它们:
#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;
}
请注意,调用begin()或end()将始终提供合理的迭代器
但是类似:
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.
在您的代码中,总是在重复使用迭代器时,不会对向量进行中间修改,因此也不会导致无效。
调整大小和插入时,迭代器可能会失效。 擦除仅会使被擦除元素处或之后的迭代器无效。
至少,这些是std::vector
的释义规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.