Reverse iterators

suggest change

If we want to iterate backwards through a list or vector we can use a reverse_iterator. A 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.

For instance, to iterate backwards use:

std::vector<int> v{1, 2, 3, 4, 5};
for (std::vector<int>::reverse_iterator it = v.rbegin(); it != v.rend(); ++it)
{
    cout << *it;
} // prints 54321

A reverse iterator can be converted to a forward iterator via the base() member function. The relationship is that the reverse iterator references one element past the base() iterator:

std::vector<int>::reverse_iterator r = v.rbegin();
std::vector<int>::iterator i = r.base();
assert(&*r == &*(i-1)); // always true if r, (i-1) are dereferenceable
                        // and are not proxy iterators

 +---+---+---+---+---+---+---+
 |   | 1 | 2 | 3 | 4 | 5 |   |
 +---+---+---+---+---+---+---+
                        
   |   |               |   |
rend() |         rbegin()  end()
       |                   rbegin().base()
     begin()
     rend().base()

In the visualization where iterators mark positions between elements, the relationship is simpler:

+---+---+---+---+---+
| 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+
↑                   ↑
|                   |
|                 end()
|                 rbegin()
begin()             rbegin().base()
rend()
rend().base()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Iterators:
* Reverse iterators

Table Of Contents
8 Arrays
11 Loops
36 Iterators
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype