c++ - 如何使 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# - Html.listboxfor() 如何捕获更改/添加项目的事件 - Jquery MVC (C#)
- python - 如何在 iframe 中使用 python-selenium 获取无头浏览器的全页截图?
- xamarin - 对象引用未设置为 httpclient.defaultrequestheaders.accept.add android xamarin 中的对象实例
- c# - 如何在具有动态条件的 linq 查询中使用 order by 子句?
- sass - 根据使用的 sass mixin 将生成的 css 代码从 scss 源拆分为多个 css 文件
- ajax - 流程图上的 Json 返回结果图
- url - 在 URL power Bi 中应用过滤器
- go - 如何返回第一个http响应以回答
- google-cloud-platform - Stackdriver IoT 设备监控
- angular - 我想让这个角度代码返回多个结果而不是一个