Your problem is very easy to solve:
vector<int>::iterator b = v.begin( );
b++;
v.insert( b, 2 );
while( b != v.end( ) ) {
...
As is standard:
std :: 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.
Which, in a free translation, comes to say that if the new size size( )
is greater than the previous size capacity( )
, the vector can be relocated in memory, which entails invalidation of all iterators.
In other words, if making a site for new elements requires to resize the memory block used by the vector< >
, the iterators will stop targeting to the right place, and subsequent uses of them will give undefined results.
In your case, to solve the problem, just add b = v.begin( )
just after v.insert( )
:
v.insert( b, 2 );
b = v.begin( );
Another possible solution is to increase the current capacity( )
before to add, for which reserve( )
is used:
v.reserve( v.size( ) + 1 );
vector< int >::iterator b = v.begin( );
b++;
v.insert( b, 2 );
while( b != v.end( ) ) {
...