Writing Our Own Range Adaptor
Learn to implement a custom range adaptor in this lesson.
We'll cover the following...
The standard library contains a series of range adaptors that can be used for solving many different tasks. More are being added in newer versions of the standard. However, there can be situations when we’d like to create our own range adaptor to use with others from the range library. This is not actually a trivial task. For this reason, in this final lesson of the section, we’ll explore the steps we need to follow to write such a range adaptor.
The step_view
range adaptor
For this purpose, we’ll consider a range adaptor that takes every Nth element of a range and skips the others. We’ll call this adaptor step_view
. We can use it to write code as follows:
for (auto i : std::views::iota(1, 10) | views::step(1))std::cout << i << ' ';std::cout << std::endl;for (auto i : std::views::iota(1, 10) | views::step(2))std::cout << i << ' ';std::cout << std::endl;for (auto i : std::views::iota(1, 10) | views::step(3))std::cout << i << ' ';std::cout << std::endl;for (auto i : std::views::iota(1, 10) | views::step(2) | std::views::take(3))std::cout << i << ' ';std::cout << std::endl;
The first loop will print all the numbers from one to nine. The second loop will print all the odd numbers, 1, 3, 5, 7, 9. The third loop will print 1, 4, 7. Lastly, the fourth loop will print 1, 3, 5.
To make this possible, we need to implement the following entities:
A class template that defines the range adaptor
A deduction guide to help with class template argument deduction for the range adaptor
A class template that defines the iterator type for the range adaptor
A class ...