1

I am confused by the iterator:

vector<int> v;
auto begin = v.begin(), end = v.end();
while (begin != end)
{
    begin = v.insert(begin, 4);
    begin++;
}

the end iterator is invalidated, and the loop can't stop.I don't know why, for the end iterator hasn't been changed after being initialized. Besides I used to consider iterator as pointer for convenience.

Kirill Kobelev
  • 9,758
  • 6
  • 24
  • 46
Jutta
  • 465
  • 5
  • 11
  • 3
    For `std::vector`, [**all** iterators are invalidated](http://en.cppreference.com/w/cpp/container/vector/insert) after calling `insert` if it causes the vector's `size()` to exceed its `capacity()` (i.e. it must reallocate). – Cornstalks Jan 25 '16 at 04:42
  • Inserting into a vector will change where the end is... – M.M Jan 25 '16 at 05:33

3 Answers3

0

This question lists iterator invalidation rules. Modifying the data structure by resizing ("as per insert/erase [23.2.4.2/6]") invalidates the iterator, even the end() as you've noticed.

Community
  • 1
  • 1
e0k
  • 6,246
  • 2
  • 18
  • 28
0

From http://en.cppreference.com/w/cpp/container/vector/insert

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.

In your case, the call v.insert(begin, 4) invalidates all iterators since the vector is empty to start with.

As a defensive coding strategy, it is better not to rely on any iterators after a call to insert().

R Sahu
  • 196,807
  • 13
  • 136
  • 247
0

First of all. STL iterators are the same insecure as pointers. Good or bad, this is so. We cannot change this. This means that you need to be careful when you are working with iterators.

Now what happens behind the scenes. Both iterators are essentially pointers. First one points to the current beginning of the vector body, the second one to the current end of the vector body. During insertion vector is allowed to move body of the vector to some other place. If vector will move the body, your iterator end will continue pointing to the same place. Even if vector will not move the beginning of the vector (sometimes this happens), your iterator will point to the last valid element (not after that last one as it should in normal case). Again, this will not be what you are expecting.

What is written above is just for understanding. You should never use this knowledge. You should check what actions invalidate what types of iterators and base your code only on what is explicitly allowed in the documentation.

Kirill Kobelev
  • 9,758
  • 6
  • 24
  • 46