The following code won't compile
some_vector.erase(some_vector.rbegin(), some_vector.rbegin()+1);
This is just an example, I know there's better option for deleting the last n elements. GCC tells me that there is no matching function for erase. Did I do something wrong or does erase not work with reverse iterators ? It works fine with a forward iterator, though
C++ Vector Library - rbegin() FunctionThe C++ function std::vector::rbegin() returns a reverse iterator which points to the last element of the vector. Reverse iterator iterates reverse order that is why incrementing them moves towards beginning of vector.
You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector. erase(std::remove(myVector. begin(), myVector.
C++ Iterators Reverse IteratorsA reverse iterator is made from a bidirectional, or random access iterator which it keeps as a member which can be accessed through base() . To iterate backwards use rbegin() and rend() as the iterators for the end of the collection, and the start of the collection respectively.
It does not. However, reverse iterators provide a base()
method to obtain a forward iterator. Take note that the returned forward iterator points to the element following the element the reverse iterator points to.
Or, to put it another way, .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 swap 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 without swapping the order of the reverse iterators this wouldn't be true. So if we have two reverse iterators a
and b
, and b >= a
then we can use this idiom for erase()
:
container.erase(b.base(), a.base());
More generally, it holds for the range of reverse iterators [a, b) that the range [b.base(), a.base()) iterates the same sequence of elements in the opposite order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With