Erase member function of vector class

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
std::vector::erase
Invalidates iterators and references at or after the point of the erase, including the end() iterator.

Return value: Iterator following the last removed element. If the iterator pos refers to the last element, the end() iterator is returned.
http://en.cppreference.com/w/cpp/container/vector/erase


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>

int main() {

    std::vector<int> v { 2, 5, 7, 9 };

    std::vector<int>::iterator it = v.begin() ;

    while( it != v.end() ) {

        std::cout << "erase " << *it << '\n' ;
        it = v.erase(it) ; // returns the iterator to the element just after the
                           // removed element, or end() if there is no such element
    }
}
Topic archived. No new replies allowed.