gpt4 book ai didi

c++ - 为什么我不能像这样删除 vector 的所有元素?

转载 作者:行者123 更新时间:2023-11-30 01:49:28 25 4
gpt4 key购买 nike

我崩溃的源代码在这里:

#include <vector>
using namespace std;
vector<int>::iterator iter , tempIt;
int main() {
vector<int> cont(3, 5);
for (iter = cont.begin() ; iter != cont.end() ; ) {
tempIt = iter;
++iter;
cont.erase(tempIt);
}
return 0;
}

删除最后一个元素总是失败。

最佳答案

来自 http://en.cppreference.com/w/cpp/container/vector/erase :

Invalidates iterators and references at or after the point of the erase, including the end() iterator.

因此删除会使您的 iter 迭代器无效,之后您将有未定义的行为。

关于c++ - 为什么我不能像这样删除 vector 的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29078121/

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