According to the C ++ specification (23.2.4.3), vector :: erase () only invalidates "all iterators and references after the erase point"
Thus, when using reverse_iterators to transmit all elements of a vector, erasing on the current iterator should not invalidate the rend () member.
This code will work under g ++, but will throw a run-time 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);
for(vector<int>::const_iterator i = x.begin(); i != x.end(); ++i)
printf("%d\n", *i);
for(vector<int>::reverse_iterator r = x.rbegin(); r != x.rend(); ++r)
if(*r == 2)
x.erase((r+1).base());
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 does not decrease
Indicated on the line of the second cycle for the second run. The decrease refers to the internal “current” member of the iterator iterator iterator, which decreases each time the iterator is incremented.
Can someone explain this behavior please?
Thank.
EDIT
, , r, rend():
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());
}
vector iterators incompatible for .