C++ 11中lambda表达式的基本写法格式为:
[capture](parameters) -> return_type { /* ... */ }
其中 [] 内为外部变量的传递方式:
[] //no variables defined. Attempting to use any external variables in the lambda is an error. [x, &y] //x is captured by value, y is captured by reference [&] //any external variable is implicitly captured by reference if used [=] //any external variable is implicitly captured by value if used [&, x] //x is explicitly captured by value. Other variables will be captured by reference [=, &z] //z is explicitly captured by reference. Other variables will be captured by value
() 内为参数,比如:
[](int x, int y) -> int { return x + y; }
return_type就是字面上的意思,也就是返回类型或者说函数类型。{}内则是我们编写的函数要执行的功能代码。
我们知道,要执行函数则需要调用函数名,但匿名函数没有函数名(匿名函数最大的好处就是以后定义函数不用再纠结给函数命什么名了),因而突然间拿到一个lambda表达式,我们会突然间有点迷惑,不知道该怎么样执行它。
下面代码则给了几个调用并执行匿名函数的方式:
#include <iostream>
#include <vector>
#include <string>
#include <functional> /** function */
#include <algorithm> /** for_each */
/** 建立一个类似创建线程函数的用法的函数来完成执行匿名函数 */
int my_eval(std::function <int(int, int)> f, int x, int y) {
return f(x, y);
}
int main() {
/**用法1: 通过将匿名函数存储在变量中,并作为参数传递*/
std::function<int(int, int)> f0 = [](int x, int y) -> int {return x + y; };//lambda 表达式
auto f1 = [](int x, int y) -> int {return x * y; };//没有使用任何外部变量
std::cout << "f0: " << my_eval(f0, 3, 4) << std::endl;
std::cout << "f1: " << my_eval(f1, 2, 3) << std::endl;
/**用法2: 保存到vector中*/
std::vector<decltype(f0)> func_s{ f0, f1 };
func_s.push_back([](int x, int y) {return x - y; });
for (auto f : func_s)//遍历匿名函数
std::cout << "f: " << f(3, 1) << std::endl;
/**用法3: 使用for_each传入匿名函数*/
std::vector<int> nums{ 1,2,3,4,5 };
int sum = 0;
//代码中使用了sum 因而通过[&]引用隐式捕获,如果代码没有使用任何外部变量,则不传递参数
std::for_each(begin(nums), end(nums), [&](int x) {sum += x; });
//x为遍历nums传递的值
std::cout << "f3: " << sum << std::endl;
//同上用法 但匿名函数参数有不同的地方
std::string str{ "hello world" };
std::string s = "";
std::string c = " ";
//指明外部变量s通过引用捕获,c通过传递值捕获
std::for_each(begin(str), end(str), [&s, c](char x) {s += (x + c); });
std::cout << "f4: " << s << std::endl;
/**用法4: 保存到函数指针*/
auto my_lambda_func = [](int x) {std::cout << "f5: " << x << std::endl; };
void(*func_ptr)(int) = my_lambda_func;
func_ptr(4);//回调
return 0;
}
运行结果:

参考资料: