C++:在 <numeric> 的累积方法中使用 Lambda 函数

Gio*_*gre 1 c++ lambda c++11

我有一个二维vector< vector<int> >,比如说

\n

contests = [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]]

\n

我想用accumulate获取第一个元素的总和,因此我使用 lambda 函数来访问向量向量中的正确维度:

\n
#include <iostream>\n#include <vector>\n#include <numeric>\n\nint main() {\n    std::vector< std::vector<int> > \n        contests = {{5, 1}, {2, 1}, {1, 1}, {8, 1}, {10, 0}, {5, 0}};\n    int sum = std::accumulate(contests.begin(),contests.end(), 0, \n                  [](const std::vector<int>& a, const std::vector<int>& b)->int \n                      {return a[0] + b[0];}\n              );\n    \n    std::cout << sum << std::endl;\n    \n    return 0;\n} \n
Run Code Online (Sandbox Code Playgroud)\n

结果我得到一个很长的编译错误,最后一行指出:

\n
    note: candidate: \xe2\x80\x98main(int, std::vector<std::vector<int> >)::<lambda(const std::vector<int>&, const std::vector<int>&)>\xe2\x80\x99\n                     [](const vector<int>& a, const vector<int>& b)->int {return a[0] + b[0];}\n                                                       ^~~\nmain.cpp:37:55: note:   no known conversion for argument 1 from \xe2\x80\x98int\xe2\x80\x99 to \xe2\x80\x98std::vector<int>\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n

如何让 lambda 识别正确的参数?

\n

raw*_*rex 5

问题来自于传递函子中的参数类型。让我们看一下文档:

\n
\n

...将应用的二元运算函数对象。二进制\n运算符采用当前累加值 a(初始化为 init)\n和当前元素的值 b- cppreference.com

\n
\n

这正是错误消息所说的:no known conversion from \xe2\x80\x98int\xe2\x80\x99 to \xe2\x80\x98std::vector<int>\xe2\x80\x98,因为std::accumulate将当前累积值 anint传递给需要 a 的函子std::vector<int>作为其第一个参数的函子。

\n

因此,您的函子必须具有以下形式:

\n
// Pass currently accumulated value and the value of the current element\n[](int current, const std::vector<int>& b)->int {return current + b[0];}\n
Run Code Online (Sandbox Code Playgroud)\n

例子:

\n
std::vector<std::vector<int>>\n    contests = {{5, 1}, {2, 1}, {1, 1}, {8, 1}, {10, 0}, {5, 0}};\n\nint sum = std::accumulate(contests.begin(), contests.end(), 0, \n          [](int current, const std::vector<int>& b)->int {return current + b[0];});\n\nstd::cout << sum << std::endl;\n
Run Code Online (Sandbox Code Playgroud)\n

印刷:

\n
31\n
Run Code Online (Sandbox Code Playgroud)\n