Sometimes, it is valuable to iterate over a range the other way around, not forward but backward. The range-based for
loop, as well as all STL algorithms usually iterate over the given ranges by incrementing iterators, although iterating backward requires decrementing them. Of course, it is possible to wrap iterators into a layer that transforms an increment call effectively into a decrement call. This sounds like a lot of boilerplate code for every type on which we would like to support that.
The STL provides a helpful reverse-iterator adapter, which helps us set up such iterators.
In this section, we will use reverse iterators in different ways, just to show how they are used:
- We need to include some headers first, as always:
#include <iostream> #include <list> #include <iterator>
- Next, we declare that we use namespace
std
in order to spare us some typing:
using namespace std...