I wrote this small code just to see how an iterator actually gets invalidated and does not point to changed location of a vector after its capacity is reached.
Here the size of vector and capacity is both 5 initially . After that I inserted a few other elements in vector and does not re-initialize my iterator to point to myvector.begin()
. This lead to a junk value of 49
in my output after maximum size of vector is : 1073741823
when printing elements of vector again.
My question is why C++ does not make point iterator again to a valid myvector.begin()
after all elements are copied into new location?
This can also lead to some behavior which can be hard to debug. I know a safe way to work would be to always reinitialize the iterator just before using it.
#include<iostream>
#include<vector>
#include<stdio.h>
using namespace std;
int main()
{
vector<int> myvector;
vector<int>::iterator it;
int myarray[]= {100,200,300,400};
myvector.insert(it,500);
it=myvector.begin();
myvector.insert(it,myarray,myarray+4);
it=myvector.begin();
for(;it!=myvector.end();++it)
cout <<*it<<endl;
cout <<"size of vector is :" << myvector.size() <<"\n";
cout <<"capacity of vector is : " << myvector.capacity()<<"\n";
cout <<"maximum size of vector is : " << myvector.max_size()<<"\n";
myvector.push_back(600);
for(;it!=myvector.end();++it)
cout <<*it<<endl;
}
Output of program :-
100
200
300
400
500
size of vector is :5
capacity of vector is : 5
maximum size of vector is : 1073741823
49
100
200
300
400
500
600
std::vector
anything which changes the size invalidates previous iterators – Flexobegin()
'just in case'. See here for info revector
- sgi.com/tech/stl/Vector.html – Steve Townsend