c++ - 调用删除后迭代器无效

标签 c++ stl

我有点困惑。我了解到或被告知的是,如果调用删除, vector 的迭代器将变得无效。但为什么下面的代码有效。它使用g++编译并在Linux中运行。

#include <vector>
#include <iostream>

using namespace std;

int main() {
  vector<int> vec;
  vec.push_back(1);
  vec.push_back(2);
  vec.push_back(3);

  vector<int>::iterator it = vec.begin();
  ++it;
  vector<int>::iterator it2;

  it2 = vec.erase(it);
  cout << "it: " << *it << endl;
  cout << "it2: " << *it2 << endl;
}

感谢您的反馈!

最佳答案

来自http://www.cplusplus.com/reference/stl/vector/erase/ (不是世界上最好的 C++ 引用):

This invalidates all iterator and references to position (or first) and its subsequent elements.

所以是无效的;使用它会导致未定义的行为。事实上,你碰巧得到了你所期望的东西,这纯粹是运气不好。

关于c++ - 调用删除后迭代器无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9310263/

相关文章:

c++ - 使用 Eclipse 时如何向我的 C++ 编译可执行文件添加图标?

c++ - 错误 C2248 : 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'

c++ - 初始化 epoll,它在 C++ 中是静态的

c++ - 将派生类作为值放入 STL 映射中

c++ - c++中关于map的初值假设

c++ - mfc 复制 CString 的某些部分

c++ - 如何为 Windows Phone 8 安装 libcurl

C++:是为循环内声明的变量释放的内存

c++ - LNK2001 使用自定义结构的 std::vector

用于列表和 map 的 C++ 容器