Create an Iterable Range
Learn to create an iterable range.
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
Seq
class. 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_}; }};
...
Get hands-on with 1400+ tech skills courses.