C++迭代器有效性问题

标签 c++ iterator

我正在从 http://www.cplusplus.com/reference/vector/vector/insert/ 学习 std::vector::insert 相关部分代码:

int main ()
{
  std::vector<int> myvector (3,100);
  std::vector<int>::iterator it;

  it = myvector.begin();
  it = myvector.insert ( it , 200 );

  myvector.insert (it,2,300);

  // "it" no longer valid, get a new one:
  it = myvector.begin();

为什么.insert操作后迭代器无效?

最佳答案

来自 this reference它说:

Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.

关于C++迭代器有效性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31873475/

相关文章:

iterator - 找出闭包的返回类型

c++ - 谷歌/基准测试结果不一致

c++ - 在用户上下文中从守护进程启动代理

c++ - 当底层 QMainwindow 有背景图像时 QLabel 不透明度问题

java - 交错迭代器方法

rust - 为什么不可能取消引用装箱的迭代器特征对象?

ruby - 获取多个数组中所有值的每个组合

const 类型的构造函数初始值设定项的 C++ 正确输入验证

c++ - std::function<void(int&)> 类型的大小

java - 我正在尝试实现我自己的 HashSet,但我不知道 iterator() 方法应该返回什么?