首页 > 解决方案 > 如何使 for_each 采用带有 2 个参数的 lambda 函数?

问题描述

我正在尝试制作lambda带有 2 个参数并返回它们之和的函数,然后将此函数传递给for_each循环以将每个 2 个元素加在一起。但是由于for_each让函数作用于当前元素,我不能将当前元素和下一个元素加在一起!

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector <int> v = {1, 2, 4, 54 ,64, 32, 43, 3};
    auto add = [](int x, int y) {cout <<  (x+y) << endl;};
    for_each(v.begin(), v.end(), add);
}

但这会产生错误,我尝试通过以下方式手动处理:

vector <int> v = {1, 2, 4, 54 ,64, 32, 43, 3};
    auto add = [](auto x) {auto s = x + *(&x+1); //adding the current element and the next elemnt.    
                            cout << s << endl;};
    for_each(v.begin(), v.end(), add) ;

输出 :

7077509
7077510
7077512
7077562
7077572
7077540
7077551
7077511

我不知道这个额外的7077508数字是从哪里来的!如果容器不是关联的,这将不起作用。那么如何制作这个add函数需要2个参数。

标签: c++lambdaforeach

解决方案


推荐阅读