STL算法传递信息方式:函数指针、函数符 (函数对象) 和 lambda .
lambda 函数的使用示例:
vectornumbers{1, 2, 3, 4, 5, 6}; int count3; count3 = count_if(numbers.begin(), numbers.end(), [](int x) { return x % 3 == 0; });
lambda 函数使用 [] 代替函数名(这就是匿名的由来)
可以不声明返回类型,当没有声明返回类型时,相当于使用 decltype 根据返回值推断。这里为 bool . 也可以声明返回类型,如下面代码所示:
count3 = count_if(numbers.begin(), numbers.end(), [](int x) -> bool {
return x % 3 == 0;
});
也可以给 lambda 函数指定一个名称,如:
auto mod3 = [](int x){return x % 3 == 0;} // mod3 a name for the lambda
count1 = std::count_if(n1.begin(), n1.end(), mod3);
count2 = std::count_if(n2.begin(), n2.end(), mod3);
函数指针方法阻止内联,lambda 和 函数符不阻止内联。The relative efficiencies of the three approaches boils down to what the compiler chooses to inline. Here, the function pointer approach is handicapped by the fact that compilers traditionally don’t inline a function that has its address taken because the concept of a function address implies a non-inline function.With functors and lambdas, there is no apparent contradiction with inlining.
lambda 有一些额外的功能。具体地说,lambda 可访问作用域内的任何动态变量;要捕获要使用的变量,可将其名称放在中括号内。如果只指定了变量名,如[z],将按值访问变量;如果在名称前加上&,如 [&count],将按引用访问变量。[&]让您能够按引用访问所有动态变量,而[=]让您能够按值访问所有动态变量。还可混合使用这两种方式,例如,[ted, &ed] 让您能够按值访问 ted 以及按引用访问ed,[&, ted] 让您能够按值访问 ted 以及按引用访问其他所有动态变量,[=,&ed]让您能够按引用访问 ed 以及按值访问其他所有动态变量。
综上,lambda 函数有以下特性:
- lambda 函数使用 [] 代替函数名
- 可以不声明返回类型(当没有声明返回类型时,相当于使用 decltype 根据返回值推断)
- 可以给 lambda 函数指定一个名称
- lambda 不阻止内联
- 可在[] 自定义按值和/或按引用访问作用域内的任何动态变量。
参考资料
[1] C++.Primer.Plus.6th.Edition



