why is the iterator no longer valid in this example?

Hi,

I'm reading about vectors att this site (cplusplus.com) and came across the section about the member function insert. In the code below an iterator is created which points to the first element in myvector. The iterator is used to assign different numbers to myvector. At row 17 the example suddenly says that the iterator is no longer valid, why is this? In my mind the iterator is still pointing to the first element in myvector (and if I take away that line I still get the same end result). Could someone maybe explain this?

Thanks!
/Skorpan

EDIT: also what is happening at row 12?

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

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
31
// inserting into a vector
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector (3,100);
  vector<int>::iterator it;

  it = myvector.begin();
  it = myvector.insert ( it , 200 ); // what is happening here?

  myvector.insert (it,2,300);

  // "it" no longer valid, get a new one:
  it = myvector.begin(); // why do you have to get a new one?

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

  cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    cout << " " << *it;
  cout << endl;

  return 0;
}
Last edited on
Whenever you add a new element into a vector, the vector might have to reallocate the entire underlying array if there's no unused memory left. If it reallocates, you'll be left with an iterator pointing to the freed memory.

EDIT: on line 12, you're inserting an element (initialized to 200) at the position pointed to by iterator it, and making it point to the inserted element.
Last edited on
Ah, of course. Thank you very much filipe!
Topic archived. No new replies allowed.