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;
- For the sake of having something to iterate over, let's instantiate a list of integers:
int main()
{
list<int> l {1, 2, 3, 4, 5};
- Now let's print these integers in the reverse form. In order to do that, we iterate over the list by using the rbegin and rend functions of std::list and shove those values out via the standard output using the handy ostream_iterator adapter:
copy(l.rbegin(), l.rend(), ostream_iterator<int>{cout, ", "});
cout << 'n';
- If a container does not provide handy rbegin and rend functions but at least provides bidirectional iterators, the std::make_reverse_iterator function helps out. It accepts normal iterators and converts them to reverse iterators:
copy(make_reverse_iterator(end(l)),
make_reverse_iterator(begin(l)),
ostream_iterator<int>{cout, ", "});
cout << 'n';
}
- Compiling and running our program yields the following output:
5, 4, 3, 2, 1,
5, 4, 3, 2, 1,