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

标签 c++

我崩溃的源代码在这里:

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

相关文章:

c++ - 与模板类型相关的编译时错误发生在理论上不会发生的地方

c++ - 指向父类成员方法的指针

c++ - 将 XMMATRIX 转换为 D3DXMATRIX

c++ - 如何在 C++ 中将 chrono::seconds 转换为 HH:MM:SS 格式的字符串?

c++ - 64 位 C++ 中的 sizeof(long)

c++ - 在可变参数模板类中初始化数组

c++ - 使用 clock() 函数安排任务时出现问题

c++ - 来自不同线程的 Poco 日志行相互覆盖

c++ - boost 等效于 ManualResetEvent?

c++ - std::vector<{QString,int*}> 的奇怪行为