Q:

Re-using iterator after 'insert' into vector

I need some clarification regarding vector and iterator.  I have a vector of my_object, and an iterator for that vector. I perform an insert at the iterator position, and a second insert at the same location:
myiteratornew = (my_vector).insert(myiterator, my_object1);
myiteratornew = (my_vector).insert(myiterator, my_object2);

After using several times this function on several kind of 'input' data, today I get a memory error.  Of course I think the problem is caused by the use of the old iterator on the modified (reallocated) vector; modifying the code this way now it works:
myiteratornew = (my_vector).insert(myiterator, my_object1);
myiteratornew = (my_vector).insert(myiteratornew , my_object2);

My question is, how is it possible that I used my code several times without getting the memory error?  Should the second code prevent my code causing a memory error?

A:

If inserting a value into the vector will cause its size to become bigger that its capacity, a reallocation will happen. In this case, all iterators and references are invalidated. 
Otherwise, only the iterators and references before the insertion point remain valid. The iterators and references after the insertion point, as well as past-the-end iterator are invalidated as well.
That is most likely what happens to you - you are trying to use an iterator that is no longer valid. That is also why your second example is working as expected - getting a new iterator, and inserting by it is the exactly right thing to do.

