I wrote this little code to see how the iterator actually becomes invalid and does not indicate a change in the location of the vector after reaching its capacity.
Here the size of the vector and capacitance is first 5. After that, I inserted several other elements into the vector and did not reinstall my iterator to point to myvector.begin(). This leads to an undesirable value 49in my output after maximum size of vector is : 1073741823re-printing the elements of the vector.
My question is why does C ++ not make the point iterator valid again myvector.begin()after all the elements are copied to a new location?
It can also lead to some behavior that is difficult to debug. I know that a safe way to work will be to always repeat the iterator initialization immediately 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
source
share