Use reverse iterator adapters to iterate backward
A reverse iterator adapter is an abstraction that reverses the direction of an iterator class. It requires a bidirectional iterator.
How to do it…
Most bidirectional containers in the STL include a reverse iterator adapter. Other containers, such as the primitive C-array, do not. Let's look at some examples:
- Let's start with the
printc()
function we've used throughout this chapter:void printc(const auto & c, const string_view s = "") { if(s.size()) cout << format("{}: ", s); for(auto e : c) cout << format("{} ", e); cout << '\n'; }
This uses a range-based for
loop to print the elements of a container.
- The range-based
for
loop works even with primitive C-arrays, which have no iterator class. So, ourprintc()
function already works with a C-array:int main...