Consider the toy program (post.cpp):
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int > a;
int i;
for(i=0;i<10;i++)
a.push_back(i);
auto it=a.rbegin();
while(it!=a.rend()) {
if ((*it % 2)==0) {
cout << "about to erase "<<*it<<endl;
a.erase((it++).base());
}
else {
++it;
}
}
for(auto it2=a.begin(); it2 != a.end(); it2++) {
cout << *it2 << endl;
}
return 0;
}
What I am trying to do is to test for evenness, and then delete the current number, since (it++)
should return the current iterator and then advance the iterator. This is what I get as the output:
$ ./post
about to erase 8
about to erase 6
about to erase 4
about to erase 2
about to erase 0
0
2
4
6
8
If, however, I change the line a.erase((it++).base());
to a.erase((++it).base());
, I get the correct behavior. Why is this?
Useful clarification: I am using base()
since reverse_iterators cannot be used in erase()
. There is an application where I want to go reverse on the vector to erase stuff.