Iterators as generators

Looking deeper into the iterator concept, one can see that it does not actually need to point to actual data; we could simply generate values on the fly. Here is a simple implementation of a forward iterator that generates integers on the fly. It only fulfills two iterator categories; forward_iterator and input_iterator:

class IntIterator {public:  IntIterator(int v) : v_{v} {}  auto operator==(const IntIterator& it)const{ return v_ == it.v_; }  auto operator!=(const IntIterator& it)const{ return !(*this==it); }  auto& operator*() const { return v_; }  auto& operator++() { ++v_; return *this; }private:  int v_{};};

The IntIterator can then be used to iterate an increasing range of integers just like if it was a container ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.