与 C++ 中的循环和变异向量混淆

Confused with loop and mutate vector in c++

#include <iostream>
#include <vector>

using namespace std;
int main(int argc, const char *argv[]) {

  vector<int> v{0, 1, 2, 3, 4};

  for (auto it = v.begin(), e = v.end(); it != e; ++it) {
    const int x = *it;
    cout << x << endl;
    v.push_back(x);
  }
  return 0;
}

我是c++的新手,我有这个程序,我认为答案应该是0 1 2 3 4。但实际上输出是0 0 2 3 4。我想知道原因thx。

您调用了未定义的行为。 v 调整大小时(这很可能发生在第一个 push_back 上),所有现有的迭代器都将变为无效。在这种情况下,您不能依赖任何特定行为。您没有以半无限循环结束的唯一原因是您也缓存了 end 迭代器,并且两个无效迭代器指向旧内存并且有点像预期的那样工作(但可能不在不同的编译器、OS、运行时库、月相等)。