What is the correct way of filtering the output of group_by with Range-v3?

284 Views Asked by At

The following code does not compile because x cannot be compared with a std::vector<int>, as x is a more complex structure handled by Range-v3 (which is good, because it's lazy, unlike std::vector<int>).

How can I write the filtering lambda to cope with that, possibly without forcing an unnecessary conversion of x to std::vector<int>?

#include <range/v3/view/filter.hpp>
#include <range/v3/view/group_by.hpp>
#include <vector>

int main() {
    std::vector<int> v{1,2,3,4,5};
    auto w = v
        | ranges::views::group_by([](auto const& c1, auto const& c2){ return c1 == 3 && c2 == 4; })
        | ranges::views::filter([](auto const& x){ return x != std::vector<int>{3,4}; });
}
1

There are 1 best solutions below

1
On BEST ANSWER

You might still transform the view into vector:

 | ranges::views::filter([](auto const& x){ return (x | ranges::to_vector) != std::vector<int>{3,4}; });

Demo

or without converting to vector, use ranges::equal:

ranges::view::filter([](auto const& x){ return !ranges::equal(x, std::vector<int>{3,4}); })

Demo