Does resizing a vector invalidate iterators?

c++, iterator, vector

Solution

Edited with more careful wording

yes, resizing a vector might invalidate all iterators pointing into the vector.

The vector is implemented by internally allocating an array where the data is stored. When the vector grows, that array might run out of space, and when it does, the vector allocates a new, bigger, array, copies the data over to that, and then deletes the old array.

So your old iterators, which point into the old memory, are no longer valid. If the vector is resized downwards (for example by `pop_back()`), however, the same array is used. The array is never downsized automatically.

One way to avoid this reallocation (and pointer invalidation) is to call `vector::reserve()` first, to set aside enough space that this copying isn't necessary. In your case, if you called `a.reserve(3)` before the first `push_back()` operation, then the internal array would be big enough that the `push_back`'s can be performed without having to reallocate the array, and so your iterators will stay valid.

Problem

I found that this C++ code: ``` vector<int> a; a.push_back(1); a.push_back(2); vector<int>::iterator it = a.begin(); a.push_back(4); cout << *it; ``` print some big random number; but if you add `a.push_back(3)` between 3rd and 4th lines, it will print 1. Can you explain it to me?

Original source