In the following code, the iterator points to the next element of deleted element of vector.
Can you please explain it to me.
Thank you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int arr[]={2,5,7,9};
vector<int> v(arr,arr+sizeof(arr)/sizeof(int));
vector<int>::iterator it;
int i(1);
while (it!=v.end()){
it=v.begin();
cout<<"round "<<i<<":"<<endl;
cout<<"The first vector element before erasing: "<<*it<<endl;
v.erase(it);
cout<<"The value that iterator contains after erasing: "<<*it<<endl;
cout<<"The first vector element after erasing: "<<v.front()<<endl;
i++;
}
}
| |
OUTPUT:
round 1:
The first vector element before erasing: 2
The value that iterator contains after erasing: 5
The first vector element after erasing: 5
round 2:
The first vector element before erasing: 5
The value that iterator contains after erasing: 7
The first vector element after erasing: 7
round 3:
The first vector element before erasing: 7
The value that iterator contains after erasing: 9
The first vector element after erasing: 9
round 4:
The first vector element before erasing: 9
The value that iterator contains after erasing: 9
The first vector element after erasing: 9