Vector Insert Program

Feb 22, 2016 at 9:55pm
Why is the "it" iterator no longer valid after line 13?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// inserting into a vector
#include <iostream>
#include <vector>

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();

  std::vector<int> anothervector (2,400);
  myvector.insert (it+2,anothervector.begin(),anothervector.end());

  int myarray [] = { 501,502,503 };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  std::cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}



Last edited on Feb 22, 2016 at 9:59pm
Feb 22, 2016 at 10:34pm
Because you inserted an element that possibly required the vector to be resized, invalidating the iterators.

http://www.cplusplus.com/reference/vector/vector/insert/

Iterator validity
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
Otherwise, only those pointing to position and beyond are invalidated, with all iterators, pointers and references to elements before position guaranteed to keep referring to the same elements they were referring to before the call.
Feb 22, 2016 at 10:34pm
Because the insert may have reallocated the vector.

http://www.cplusplus.com/reference/vector/vector/insert/?kw=vector%3A%3Ainsert
See the second sentence.
Last edited on Feb 22, 2016 at 10:35pm
Feb 22, 2016 at 11:03pm
Ok thank you guys for clearing that up.
Topic archived. No new replies allowed.