Is Insertion into a vector while also accessing a vector undefined behavior?

  Kiến thức lập trình

Just stumbled upon a post that talked about reference and iterator invalidation on insertion into a vector.

But is accessing a vector by index also result in undefined behavior?
Is the below code correct?

std::vector<int> data {0, 1, 2};
for (int i = 0; i < data.size(); ++i) {
  auto end = data.size();
  // Using 'for (const auto &v : data) {' below seems to be causing segfault
  // on some platforms and not on others, but clearly is wrong use of a reference
  for (int j = 0; j < end; ++j) {
    data.emplace_back(data.at(j) + end);
  }
}

This question stems from:
Iterator invalidation rules for C++ containers

LEAVE A COMMENT