调用擦除后迭代器无效 [英] Iterator invalidity after calling erase

查看:101
本文介绍了调用擦除后迭代器无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑。我学到或被告知的是,如果擦除被调用,向量的迭代器变得无效。但为什么下面的代码工作。它使用g ++编译并在Linux中运行。

I am confused a bit. What I have learned or been told is that an iterator of a vector becomes invalid if erase is called. But why the code below works. It is compiled using g++ and run in 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 ++引用):

From http://www.cplusplus.com/reference/stl/vector/erase/ (not the world's best C++ reference):


所有迭代器和对位置(或第一个)及其后续元素的引用。

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

因此 it 无效;使用它会导致未定义的行为。事实上,你碰巧得到你期望的是纯粹的运气。

So it is invalid; using it results in undefined behaviour. The fact that you happen to get what you expect is pure bad luck.

这篇关于调用擦除后迭代器无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆