joboccara/pipes

add count end pipe

jjcasmar opened this issue · 3 comments

This is an end pipe which captures an integral type and return in that integral type the number of values that has gone through the pipe. Useful for example to filter a vector, override values directly in place and remove the unfiltered values.

    auto v1Andv2 = ranges::views::zip(v1, v2);
    ranges::actions::sort(v1Andv2);
    int count = 0;
    ranges::views::unique(v1Andv2) >>= pipes::fork(pipes::unzip(pipes::override(v1),   //
                                                                pipes::override(v2)),  //
                                                   pipes::for_each([&count](const auto &v) { count++; }));
    v1.erase(std::begin(v1) + count, std::end(v1));
    v2.erase(std::begin(v2) + count, std::end(v2));

Instead of a for_each performing the count, a specific component would be more verbose.

This is an interesting use case, thanks!
As the purpose of for_each is to allow customisation, rather than adding a component to the library, why not tacking a name on the one you're creating above?

auto counter(int& count)
{
    return pipes::for_each([&count](auto const&){ ++count; });
}

Fyi I've added a test to make sure this works.

This is a special case of issue #33.
pipes::count would be the same as pipes::transform([](auto const&){return 1;}) >>= pipes::reduce(std::sum)

Nicely spotted. I'll close this issue then.