Does vector :: erase work with reverse iterators?

The following code will not compile

some_vector.erase(some_vector.rbegin(), some_vector.rbegin()+1);

      

This is just an example, I know there is a better option for removing the last n elements. GCC tells me that there is no suitable erase function. Did I do something wrong or am I not working with reverse iterators? It works fine with a front iterator though

+3


source to share


1 answer


This is not true. However, reverse iterators provide a method base()

for obtaining a forward iterator. Note that the returned iterator points to the element following the element pointed to by the backward iterator.

Or, in other words, .rbegin().base() == .end()

and.rend().base() == .begin()

So the fixed code would look like this:

some_vector.erase(
    (++(some_vector.rbegin())).base(),
    some_vector.rbegin().base()
);

      



Note that we have to reverse the order of the iterators around since they are reverse iterators; the second argument must be an iterator that follows the first iterator in the sequence, but not replacing the order of the back iterators would be wrong. So, if we have two reverse iterators a

and b

and b >= a

, then we can use this idiom to erase()

:

container.erase(b.base(), a.base());

      

More generally, for a range of backward iterators [a, b] for range [b.base (), a.base ()), the same sequence of elements is iterated in reverse order.

+6


source







All Articles