gpt4 book ai didi

c++ - 在迭代时修改数据结构

转载 作者:IT老高 更新时间:2023-10-28 22:01:56 25 4
gpt4 key购买 nike

将元素添加到 vector 等数据结构时会发生什么迭代它。我不能这样做吗?

我试过了,它坏了:

int main() {
vector<int> x = { 1, 2, 3 };

int j = 0;
for (auto it = x.begin(); it != x.end(); ++it) {
x.push_back(j);
j++;
cout << j << " .. ";
}
}

最佳答案

迭代器因某些修改 std::vector 的操作而失效。

其他容器有关于迭代器何时失效和不失效的各种规则。 This is a post (由您真诚地)提供详细信息。

顺便说一句,入口函数main() 必须返回int:

int main() { ... }

关于c++ - 在迭代时修改数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5638323/

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