Building your own iterable range
We already realized that iterators are, kind of, the standard interface for iterations over containers of all kinds. We just need to implement the prefix increment operator, ++
, the dereference operator, *
, and the object comparison operator, ==
, and then we already have a primitive iterator that fits into the fancy C++11 range-based for
loop.
In order to get used to this a bit more, this recipe shows how to implement an iterator that just emits a range of numbers when iterating through it. It is not backed by any container structure or anything similar. The numbers are generated ad hoc while iterating.
How to do it...
In this recipe, we will implement our own iterator class, and then, we will iterate through it:
- First, we include the header, which enables us to print to the terminal:
#include <iostream>
- Our iterator class will be called
num_iterator
:
class num_iterator {
- Its only data member is an integer. That integer is used for counting. The...