C/C++ Arena

Step 3 of 5

Iterator concepts and algorithms

Standard algorithms need to know what kind of iterator they're given: can it go backwards? jump ahead in O(1)? C++20 checks this with concepts such as std::forward_iterator and std::random_access_iterator. For your iterator to qualify, it must declare a few member types:

using iterator_category = std::forward_iterator_tag;
using value_type = int;
using difference_type = std::ptrdiff_t;

and support post-increment (it++) and default construction. Then algorithms like std::find, std::count_if, and std::ranges:: versions accept it, and static_assert(std::forward_iterator<Iter>) proves it at compile time.

Your turn: make Countdown::Iterator a proper forward iterator: add the three member types, a default constructor, and post-increment. Countdown(n) yields n, n-1, ..., 1.

Previous: Writing an iterator class Next: A lazy range