Use iterator adapters to fill STL containers
An iterator is essentially an abstraction. It has a specific interface and is used in specific ways. But beyond that, it's just code and it can be used for other purposes. An iterator adapter is a class that looks like an iterator but does something else.
The STL comes with an assortment of iterator adapters. Often used with the algorithm
library, they are quite useful. The STL iterator adaptors generally fall into three categories:
- Insert iterators, or inserters, are used to insert elements into a container.
- Stream iterators read from and write to a stream.
- Reverse iterators reverse the direction of an iterator.
How to do it…
In this recipe, we'll look at a few examples of STL iterator adapters:
- We'll start with a simple function to print the contents of a container:
void printc(const auto & v, const string_view s = "") { if(s.size()) cout <...