ericniebler / range-v3

Range library for C++14/17/20, basis for C++20's std::ranges
Other
4.05k stars 437 forks source link

views::generate doesn't work with views::chunk_by #1802

Open gbeck75 opened 7 months ago

gbeck75 commented 7 months ago

The following code fails to compile but works as expected if I use iota() instead of generate()

// auto v = views::iota(10,20);
auto v = views::generate(
        [i=10u] () mutable {
            return i++;
        }) | views::take(10);

auto r = v | views::chunk_by(
            [](auto a, auto) {
                return a == 15;
            })

Is this to be expected? How can I use views::chunk_by with views::generate ?

JohelEGP commented 7 months ago

generate results in an input range. iota results in a random access range. chunk_by requires a forward range.

gbeck75 commented 7 months ago

Thank you! And how can I "generate" a forward range?

JohelEGP commented 7 months ago

Generating a forward range would mean having a regular invocable that returns the same value based on an index. You can generate a forward range with iota(0) | transform(generate_function).

gbeck75 commented 7 months ago

Unfortunately I only have an input range.

It seems the question should really be why chunk_by needs a forward range? In the example it should be possible to chunk the input range in a single pass, is there something like chunk_by which works on an input range?

JohelEGP commented 7 months ago

I'm looking at the C++ standard library implementation. The reason seems to be that the implementation needs two iterators into the range. The iterator's value type is a subrange: https://eel.is/c++draft/range.chunk.by#iter. You can probably write a version that works for input ranges.