I'm trying to get more acquainted with C++20's std::ranges
implementation, and I've come across a seemingly simple problem of which I cannot find a standard solution without rolling my own implementation.
The problem is simple: I would like to only access and process every Nth element in a range using a C++20 range-adapter. For example, I'm looking for a utility where the following:
for (auto x : std::ranges::iota_view{0, 10} | std::ranges::<some api>(3)) {
std::cout << x << " ";
}
will produce an output like:
0 3 6 9
This can of-course be accomplished with something like std::ranges::filter
-- however filter
actually accesses and processes the iterator at each value, e.g. it evaluates the expression "predicate(*it)
". For small simple ranges this is fine, but for more complex/expensive generator iterators, then evaluating *it
can be costly and undesirable since these values will be otherwise unused.
I'm looking for something more equivalent to the behavior of std::ranges::take
or std::ranges::drop
, which simply bypass the value by iterating over it, rather than accessing it.
Is there a simple, C++20 solution to accomplish this? Or will I have to roll my own with a wrapper iterator/sentinel where operator++
is done N times? This sounds like a utility that should already be part of the standard, but I can't seem to find anything fitting this description.