Reverse Iterators
The third kind of predefined iterator
adapters are reverse iterators. Reverse iterators operate in reverse. They switch the call of an
increment operator internally into a call of the decrement operator, and vice versa. All
containers can create reverse iterators via their member functions rbegin() and rend(). Consider the
following example:
Example:
The expression
coll.rbegin()
returns a reverse iterator for coll. This
iterator may be used as the beginning of a reverse iteration over the elements of the
collection. Its position is the last element of the collection. Thus,
the expression
*coll.rbegin()
returns the value of the last element. Accordingly, the expression
coll.rend()
returns a reverse iterator for coll that
may be used as the end of a reverse iteration. As usual for ranges, its position is past the end
of the range, but from the opposite direction; that is, it is the position before the first element in
the collection.
The expression
*coll.rend()
is as undefined as is
*coll.end()
You should never use operator * (or
operator ->) for a position that does not represent a
valid element.
The advantage of using reverse
iterators is that all algorithms are able to operate in the opposite direction without special code. A step
to the next element with operator ++ is redefined into a
step backward with operator --. For
example, in this case, copy() iterates over the elements of coll from
the last to the first element. So, the output of the program is as follows:
9
8 7 6 5 4 3 2 1
You can also switch "normal"
iterators into reverse iterators, and vice versa. However, in doing so the element of an iterator changes.
See Also:
No comments:
Post a Comment