我有一个二维vector< vector<int> >
,比如说
contests = [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]]
我想用accumulate
获取第一个元素的总和,因此我使用 lambda 函数来访问向量向量中的正确维度:
#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问题来自于传递函子中的参数类型。让我们看一下文档:
\n\n\n...将应用的二元运算函数对象。二进制\n运算符采用当前累加值
\na
(初始化为 init)\n和当前元素的值b
- cppreference.com
这正是错误消息所说的: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// 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例子:
\nstd::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印刷:
\n31\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
275 次 |
最近记录: |