0

I am learning about std::vector::insert from http://www.cplusplus.com/reference/vector/vector/insert/ Relevant part of the code:

int main () { std::vector<int> myvector (3,100); std::vector<int>::iterator it; it = myvector.begin(); it = myvector.insert ( it , 200 ); myvector.insert (it,2,300); // "it" no longer valid, get a new one: it = myvector.begin(); 

Why is iterator not valid after .insert operation?

2
  • 1
    Because inserting into a vector can cause a reallocation of the memory used to store the contents. Commented Aug 7, 2015 at 8:52
  • @JonathanPotter But when it became invalid after the first or second insert? Commented Aug 7, 2015 at 9:01

1 Answer 1

3

From this reference it says:

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.