C++中二元函数对应的lambda表达式

C++中二元函数对应的lambda表达式

二元函数接受两个参数,还可返回一个值。与之等价的 lambda 表达式如下:

[...](Type1& param1Name, Type2& param2Name) { // lambda code here; }

程序清单 22.4 演示了一个 lambda 表达式,并在 std::transform()中使用它将两个等长的 vector 中对
应的元素相乘,再将结果存储到第三个 vector 中。

0: #include <vector>
1: #include <iostream>
2: #include <algorithm>
3:
4: int main ()
5: {
6: using namespace std;
7:
8: vector <int> vecMultiplicand{ 0, 1, 2, 3, 4 };
9: vector <int> vecMultiplier{ 100, 101, 102, 103, 104 };
10:
11: // Holds the result of multiplication
12: vector <int> vecResult;
13:
14: // Make space for the result of the multiplication
15: vecResult.resize(vecMultiplier.size());
16:
17: transform (vecMultiplicand.begin (), // range of multiplicands
18: vecMultiplicand.end (), // end of range
19: vecMultiplier.begin (), // multiplier values
20: vecResult.begin (), // range that holds result
21: [](int a, int b) {return a * b; } ); // lambda
22:
23: cout << "The contents of the first vector are: " << endl;
24: for (size_t index = 0; index < vecMultiplicand.size(); ++index)
25: cout << vecMultiplicand[index] << ' ';
26: cout << endl;
27:
28: cout << "The contents of the second vector are: " << endl;
29: for (size_t index = 0; index < vecMultiplier.size(); ++index)
30: cout << vecMultiplier[index] << ' ';
31: cout << endl;
32:
33: cout << "The result of the multiplication is: " << endl;
34: for (size_t index = 0; index < vecResult.size(); ++index)
35: cout << vecResult[index] << ' ';
36:
37: return 0;
38: }

输出:
The contents of the first vector are:
0 1 2 3 4
The contents of the second vector are:
100 101 102 103 104
The result of the multiplication is:
0 101 204 309 416
分析:
lambda 表达式如第 17 行所示,它被用作 std::transform()的一个参数。算法 std::transform()接受两
个范围作为输入,执行二元函数指定的变换算法,并将结果存储在目标容器中。这里的二元函数是一
个 lambda 表达式,它接受两个整数作为输入,并返回相乘得到的结果。返回值被 std::transform()存储
到 vecResult 中。输出指出了两个容器的内容以及将对应的元素相乘得到的结果。

程序清单 22.4 演示了与程序清单 21.5 中的函数对象类 Multiply<>等价的 lambda 表达式。

对C++编程技术感兴趣的朋友请点击这里:零声学院C/C++服务器课程

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值