A reverse_iterator
is an iterator adapter that converts an iterator into an iterator that traverses in the opposite direction. For example, given a reverse_iterator revItr
, writing ++revItr
would cause the iterator to point to the element preceding the original element.
Unlike the other iterator adapters, reverse_iterator
takes as its template argument an iterator type that represents the type of iterator to reverse. For example, to reverse a vector<int>::iterator
, you'd use a reverse_iterator<vector<int>::iterator>
. It is highly advised that you use typedef
to make shorthands for these types!
reverse_iterator
can only reverse iterators that are bidirectional iterators or random iterators. This means, for example, that you can't reverse an ostream_iterator
, but that you can reverse a map<string, int>::iterator
or a list<double>::iterator
.
When constructing a reverse_iterator
, it is important to remember that the constructed iterator does not point to the same element as the original iterator. Instead, it points to the element one before the source iterator. This is counterintuitive, but it greatly simplifies many common tasks. For example, suppose you want to iterate over the elements of a vector
in reverse order. Then to get a reverse_iterator
that points to the last element in the range, you'd create a reverse_iterator<vector<T>::iterator>
and initialize it to the value of the vector
's end
function, since the element one before end
is the final element in the vector
. Similarly, to get the stopping point, you'd create a reverse_iterator<vector<T>::iterator>
initialized to the vector
's begin
function, since the element one before begin
is beyond the beginning of the container and acts in the same way as the end
function - defining the place an iterator will reach once it has traversed the entire container.
reverse_iterator<T>
Member Functionsreverse_iterator
that's a copy of another reverse_iterator
.Constructs a new reverse_iterator
that is equivalent to another reverse_iterator
.
reverse_iterator
pointing to the element before another iteratorConstructs a new reverse_iterator
that points to the element directly before the specified iterator.
Returns an iterator pointing in the opposite direction as this reverse_iterator
that points to the element after the element pointed to by the reverse_iterator
.