当我在 C++20 中使用范围时,为什么管道运算符不起作用?

Sam*_*tin 5 c++ functional-programming c++20

我目前正在研究《Expert C++》一书中的示例。

在第 7 章中,他们提供了以下用于将函数映射到矩阵的代码:

#include <vector>
#include <ranges>
#include <iostream>

using IntMatrix = std::vector<std::vector<int>>;

int count_evens(const std::vector<int>& number_line) {
    return std::count_if(number_line.begin(),
                         number_line.end(), [](int num){return num % 2 == 0;});
}

std::vector<int> count_all_evens(const IntMatrix& numbers)
{
    return numbers | std::ranges::views::transform(count_evens); // ERROR APPEARS HERE AT |
}

int main()
{
    IntMatrix m{{1, 2, 3}, {4, 5, 6}};
    for (auto item : count_all_evens(m)) {
        std::cout << item << " ";
    }
    std::cout << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在第 14 行收到错误消息:

could not convert 'std::ranges::views::__adaptor::operator|<const std::vector<std::vector<int> >&>((* & numbers), std::ranges::views::transform.std::ranges::views::__adaptor::_RangeAdaptor<std::ranges::views::<lambda(_Range&&, _Fp&&)> >::operator()<int (&)(const std::vector<int, std::allocator<int> >&)>(count_evens))' from 'std::ranges::transform_view<std::ranges::ref_view<const std::vector<std::vector<int> > >, int (*)(const std::vector<int>&)>' to 'std::vector<int>'
Run Code Online (Sandbox Code Playgroud)

还有其他人有这个问题吗?我正在使用 g++10 编译器。

Yak*_*ont 7

std::vector<int> count_all_evens(const IntMatrix& numbers)
{
  auto view = numbers | std::ranges::views::transform(count_evens);
  return {view.begin(), view.end()};
}
Run Code Online (Sandbox Code Playgroud)

一个建议可以减少这种情况。

std::vector<int> count_all_evens(const IntMatrix& numbers)
{
  auto view = numbers | std::ranges::views::transform(count_evens);
  return std::ranges::to<std::vector<int>>(view);
}
Run Code Online (Sandbox Code Playgroud)

你也可以随心所欲

template<class Range>
struct to_container {
  Range&& r;
  template<class Container>
  operator Container()&&{ return {r.begin(), r.end()}; }
};
template<class Range>
to_container(Range&&)->to_container<Range>;

std::vector<int> count_all_evens(const IntMatrix& numbers)
{
  return to_container{ numbers | std::ranges::views::transform(count_evens) };
}
Run Code Online (Sandbox Code Playgroud)

  • 或者只是返回“auto”,因为我们只是循环并且实际上不需要将结果收集到“向量”中 (2认同)