【问题标题】:map_reduce C++ lamba: candidate not viable single argumentmapreduce C++ lambda:候选不可行的单个参数
【发布时间】:2020-07-30 02:41:23
【问题描述】:

我写了一个小程序来使 map/reduce 在 C++ 中工作。 这里是结构:

struct Point {
    int x = 0;
    int y = 0;
};

我想选择每个点的“x”并将它们乘以一个 int。然后,我想用最终的lamba(或通过std::multiples)减少值

std::vector<Point> p = {{10,20},{20,40}};
std::vector<int> p3 (p.size());

auto totalx = transform_reduce(p.begin(), p.end(),p3.begin(), 0.0, [](Point& p){ return p.x * 23;}, [](int a, int b){return a * b;});

cout << totalx << endl;

我有这个错误:

main.cpp:28: candidate function not viable: requires single argument 'p', but 2 arguments were provided
conversion candidate of type 'int (*)(Point &)'

我真的不明白我做错了什么。

【问题讨论】:

  • transform_reduce 给出单个值,而不是输出范围。 p3的目的是什么?
  • 我认为我需要提供一个临时列表来存储 int 值。就像一个临时的整数列表。我错了……

标签: c++ lambda mapreduce c++17 reduce


【解决方案1】:

在我看来你想要:

  1. 将所有点从 (x, y) 转换为 x*23
  2. 将所有这些值相乘

在这种情况下,您应该给出:

  1. 开始
  2. 结束
  3. 初始值(在乘法的情况下,1.0 而不是 0.0)
  4. 二元运算(std::multiplies&lt;int&gt;(),或您的[](int a, int b) {return a * b; },用于减少元素之间的关系)
  5. 一元运算符映射单个元素(在您的情况下,[](const int number){return number*23;}

总体:

auto totalx = std::transform_reduce(p.begin(), p.end(), 1.0, [](int a, int b) {return a * b; }, [](const Point& p) { return p.x * 23; });

请注意,不需要输出迭代器,因为只有一个结果。

【讨论】:

  • 我没有得到 lambda 的顺序。所以,reduce 函数是第三个参数,而 map 函数是最后一个。有点奇怪 ?没有?
  • 你是对的,它被称为transform_reduce,它在转换之前接收reduce函数,但这是标准......
猜你喜欢
  • 2016-01-12
  • 2021-12-31
  • 1970-01-01
  • 2016-06-05
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
相关资源
最近更新 更多