c++c++20std-rangesrange-v3

Using zip_view piped into a filter_view


I am getting compilation erorr while trying to zip two vectors and apply and filter as below.

#include <range/v3/all.hpp>

int main()
{
    std::vector v1 = {0, 1, 2, 3, 4};
    std::vector v2 = {'a', 'b', 'c', 'd', 'e'};

    auto pred = [](auto& p) { return (p.first != 0); };

    auto x = ranges::views::zip(v1, v2);
    auto y = x | ranges::views::filter(pred);
}

Here is compilation error

<source>: In function 'int main()':
<source>:15:16: error: no match for 'operator|' (operand types are 'ranges::zip_view<ranges::ref_view<std::vector<int, std::allocator<int> > >, ranges::ref_view<std::vector<char, std::allocator<char> > > >' and 'ranges::views::view_closure<ranges::detail::bind_back_fn_<ranges::views::filter_base_fn, main()::<lambda(auto:28&)> > >')
   15 |     auto y = x | ranges::views::filter(pred);
      |              ~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
      |              |                        |
      |              |                        ranges::views::view_closure<ranges::detail::bind_back_fn_<ranges::views::filter_base_fn, main()::<lambda(auto:28&)> > >
      |              ranges::zip_view<ranges::ref_view<std::vector<int, std::allocator<int> > >, ranges::ref_view<std::vector<char, std::allocator<char> > > >
In file included from /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/regex:40,
                 from /opt/compiler-explorer/libs/rangesv3/0.12.0/include/range/v3/view/tokenize.hpp:18,
                 from /opt/compiler-explorer/libs/rangesv3/0.12.0/include/range/v3/view.hpp:81,
                 from /opt/compiler-explorer/libs/rangesv3/0.12.0/include/range/v3/all.hpp:25,
                 from <source>:4:

Solution

  • You'll need a const& in your pred:

    auto pred = [](auto const& p) { return p.first != 0; };
    

    This can also be achieved by using a forwarding reference:

    auto pred = [](auto&& p) { return p.first != 0; };
    

    Demo