Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does vector::erase not work with reverse iterators?

Tags:

c++

stl

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

like image 992
Aaa Bbb Avatar asked May 18 '17 02:05

Aaa Bbb


People also ask

How do you reverse a vector in C++ using iterators?

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.

How do I erase an element from std :: vector <> by value?

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.

How does reverse iterator works C++?

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.


1 Answers

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.

like image 68
cdhowie Avatar answered Sep 29 '22 03:09

cdhowie