Create an Iterable Range
Explore how to build a sequence generator class in C++ that supports range-based for loops by implementing an iterator with key operators like dereference, prefix increment, and not-equal comparison. Understand the design of nested iterator classes and effective container interfaces to create flexible iterable ranges.
We'll cover the following...
This recipe describes a simple class that generates an iterable range, suitable for use with the range-based for loop. The idea is to create a sequence generator that iterates from a beginning value to an ending value.
To accomplish this task, we need an iterator class, along with the object interface class.
How to do it
There's two major parts to this recipe, the main interface, Seq, and the iterator class.
First, we'll define the
Seqclass. It only needs to implement thebegin()andend()member functions:
template<typename T>class Seq {T start_{};T end_{};public:Seq(T start, T end) : start_{start}, end_{end} {}iterator<T> begin() const {return iterator{start_};}iterator<T> end() const { return iterator{end_}; }};
The constructor sets up the start_ and end_ variables. ...