实例讲解实例讲解C++编程中编程中lambda表达式的使用表达式的使用
主要介绍了C++编程中lambda表达式的使用实例,lambda表达式特性的引入在C++11中可谓千呼万唤始出来,非
常重要,需要的朋友可以参考下
函数对象与函数对象与Lambdas
你编写代码时,尤其是使用 STL 算法时,可能会使用函数指针和函数对象来解决问题和执行计算。函数指针和函数对象各有
利弊。例如,函数指针具有最低的语法开销,但不保持范围内的状态,函数对象可保持状态,但需要类定义的语法开销。
lambda 结合了函数指针和函数对象的优点并避免其缺点。lambda 与函数对象相似的是灵活并且可以保持状态,但不同的是其
简洁的语法不需要显式类定义。 使用lambda,相比等效的函数对象代码,您可以写出不太复杂并且不容易出错的代码。
下面的示例比较lambda和函数对象的使用。 第一个示例使用 lambda 向控制台打印 vector 对象中的每个元素是偶数还是奇
数。第二个示例使用函数对象来完成相同任务。
示例 1:使用 lambda
此示例将一个 lambda 传递给 for_each 函数。该 lambda 打印一个结果,该结果指出 vector 对象中的每个元素是偶数还是奇
数。
代码
// even_lambda.cpp
// compile with: cl /EHsc /nologo /W4 /MTd
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 1; i < 10; ++i) {
v.push_back(i);
}
// Count the number of even numbers in the vector by
// using the for_each function and a lambda.
int evenCount = 0;
for_each(v.begin(), v.end(), [&evenCount] (int n) {
cout << n;
if (n % 2 == 0) {
cout << "is even" << endl;
++evenCount;
} else {
cout << "is odd" << endl;
}
});
// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}
输出
1 is even
2 is odd
3 is even
4 is odd
5 is even
6 is odd
7 is even
8 is odd
9 is even
There are 4 even numbers in the vector.
批注
在此示例中,for_each 函数的第三个参数是一个lambda。 [&evenCount] 部分指定表达式的捕获子句,(int n) 指定参数列表,