Home

reverseiterator

Reverse_iterator is an iterator adapter in the C++ Standard Template Library that provides a view of a container in reverse order by wrapping another iterator, called the base iterator. It allows traversal of a sequence from end to beginning without copying or restructuring the data.

The reverse_iterator stores a base iterator and defines its operations in reverse relation to that base. Dereferencing

In practice, reverse_iterator is used via reverse iterators or range-based constructs. Typical loops look like for

Common considerations include understanding how base() relates to the element accessed by the reverse_iterator, and ensuring

a
reverse_iterator
yields
the
element
preceding
the
base
iterator’s
position,
while
incrementing
the
reverse_iterator
moves
toward
the
beginning
of
the
sequence
by
decrementing
the
base
iterator.
The
base()
member
returns
the
underlying
forward
iterator.
Containers
commonly
expose
reverse
iterators
through
rbegin()
and
rend(),
where
rbegin()
points
to
the
last
element
and
rend()
is
positioned
before
the
first.
(auto
it
=
v.rbegin();
it
!=
v.rend();
++it)
{
/*
use
*it
*/
}.
Many
standard
algorithms
also
accept
reverse
iterators
to
operate
on
ranges
in
reverse,
such
as
std::copy(v.rbegin(),
v.rend(),
out.begin())
or
std::sort(v.rbegin(),
v.rend())
for
reverse-order
sorting.
The
reverse_iterator
abstraction
is
defined
generically
as
std::reverse_iterator<Iterator>
and
can
adapt
any
bidirectional
iterator,
or
a
random-access
iterator,
depending
on
the
container’s
capabilities.
compatibility
with
algorithms
that
expect
forward
iterators.
Reverse
iterators
are
provided
by
standard
containers,
and
they
enable
concise,
efficient
reverse
traversal
without
manual
index
arithmetic
or
temporary
copies.