i writing test program on iterators in vector, in begining had created vector , initialize series of numbers 1-10.
after had created iterator "myiterator" , const iterator "iter". had used iter display contents of vector.
later on had assigned "myiterator" "anothervector.begin()". pointing same thing.
checked
//cout << /* *myiterator << */"\t" << *(anothervector.begin()) << endl;
so in second iterator loop replaced "anothervector.begin()" myiterator.
but produced different output.
code is:
vector<int> anothervector; for(int = 0; < 10; i++) { intvector.push_back(i + 1); cout << anothervector[i] << endl; } cout << "anothervector" << endl; //************************************* //iterators cout << "iterators" << endl; vector<int>::iterator myiterator; vector<int>::const_iterator iter; for(iter = anothervector.begin(); iter != anothervector.end(); ++iter) { cout << *iter << endl; } cout << "another insertion" << endl; myiterator = anothervector.begin(); //cout << /* *myiterator << */"\t" << *(anothervector.begin()) << endl; myiterator[5] = 255; anothervector.insert(anothervector.begin(),200); //for(iter = myiterator; iter != anothervector.end(); ++iter) { //cout << *iter << endl; //} for(iter = anothervector.begin(); iter != anothervector.end(); ++iter) { cout << *iter << endl; }
output using
for(iter = anothervector.begin(); iter != anothervector.end(); ++iter) { cout << *iter << endl; }
gives:
iterators 1 2 3 4 5 6 7 8 9 10 insertion 200 1 2 3 4 5 255 7 8 9 10
and output using
for(iter = myiterator; iter != anothervector.end(); ++iter) { cout << *iter << endl; }
gives:
iterators 1 2 3 4 5 6 7 8 9 10 insertion 0 0 3 4 5 255 7 8 9 10 81 0 1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 0 97 0 200 1 2 3 4 5 255 7 8 9 10
why there difference if pointing same address.
after insert
, myiterator
no longer valid. because insertion std::vector
can cause vector reallocation, , such addresses pointed prior iterators may not pointing address space of reallocated vector.