I came across "Add elements to a vector during range-based loop c++11", and wasn't surprised it's not allowed using std::vector
because the append can invalidate iterators. However, inserting into std::list
doesn't invalidate any of the iterators, so I was wondering if it would be allowed with std::list
instead of std::vector
.
e.g.
std::list<int> list({1});
for (int &cur : list)
{
std::cout << cur << " ";
if (cur < 10)
{
list.push_back(cur + 1);
}
}
It seems to compile fine, but I'm worried it's undefined behaviour.
Yes, inserting / removing elements of a
std::list
does not invalidate pointers, references, or iterators to elements, except for the removed element. Not even the end-iterator is changed or invalidated.Thus, it is safe.
But as one has to carefully ponder about safety, it is still inadvisable.