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?
// inserting into a vector
#include <iostream>
#include <vector>
usingnamespace 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;
}
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.