gpt4 book ai didi

c++ - 为什么这个 vector 迭代器不会失效?

转载 作者:行者123 更新时间:2023-11-30 00:51:06 25 4
gpt4 key购买 nike

我读过一些关于迭代器失效的帖子,似乎需要 vector 重新分配的插入会使迭代器失效。 vector 中间的删除也不应该导致失效吗?

我对此没有清楚的理解,不确定为什么在调整大小并从开始、中间和结束处删除后使用这些迭代器不会破坏它们:

#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.

关于c++ - 为什么这个 vector 迭代器不会失效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22874410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com