我崩溃的源代码在这里:
#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/