According to the C++ specification (23.2.4.3), vector::erase() only invalidates "all the iterators and references after the point of the erase"
As such, when using reverse_iterators to pass over all vector members, an erase on the current iterator should not cause the rend() member to be invalidated.
This code will run under G++ but will provide a runtime exception on Windows (VS2010):
#include <vector>
using namespace std;
int main()
{
vector<int> x;
x.push_back(1);
x.push_back(2);
x.push_back(3);
//Print
for(vector<int>::const_iterator i = x.begin(); i != x.end(); ++i)
printf("%d\n", *i);
//Delete second node
for(vector<int>::reverse_iterator r = x.rbegin(); r != x.rend(); ++r)
if(*r == 2)
x.erase((r+1).base());
//Print
for(vector<int>::const_iterator i = x.begin(); i != x.end(); ++i)
printf("%d\n", *i);
return 0;
}
The error is interesting:
Expression: vector iterator not decrementable
Given on the line of the second for loop upon the second run. The decrement refers to the internal "current" iterator member of the reverse_iterator, which is decremented whenever reverse_iterator is incremented.
Can anyone explain this behavior, please?
Thanks.
EDIT
I think this code sample better shows that it's not a problem with r, but rather with rend():
//Delete second node
for(vector<int>::reverse_iterator r = x.rbegin(); r != x.rend();)
{
vector<int>::reverse_iterator temp = r++;
if(*temp == 2)
x.erase((temp+1).base());
}
And errors out with vector iterators incompatible
on the for loop upon entry after erase.