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++服务器课程