intmain() { int a = 3,b = 4; string c = "lambda"; float d = 5.754;
auto fun = [=]{ //以复制的方式捕获当前作用域的所有变量 //a = 44; //没加 mutable 会报错 printf("1: a = %d b = %d c = %s d = %.3f\n",a,b,c.c_str(),d); }; fun();
auto fun1 = [&]{ //以复制的方式捕获当前作用域的所有变量 a = 30; b = 40; c = "lambda test"; d = 1.23455; printf("2: a = %d b = %d c = %s d = %.5f\n",a,b,c.c_str(),d); }; fun1();
auto fun2 = [a, b, &c, &d] () mutable { //a,b以复制的方式捕获c,d以引用的方式捕获 a = 300;//加了 mutable 说明符 可以修改复制方式捕获的值,但不会影响到原有的值 b = 400; c = "lambda test test"; d = 11.23455; printf("3: a = %d b = %d c = %s d = %.5f\n",a,b,c.c_str(),d); }; fun2(); printf("4: a = %d b = %d c = %s d = %.5f\n",a,b,c.c_str(),d);//a,b的值没有改变
return0; }
输出
1 2 3 4
1: a = 3 b = 4 c = lambda d = 5.754 2: a = 30 b = 40 c = lambda test d = 1.23455 3: a = 300 b = 400 c = lambda test test d = 11.23455 4: a = 30 b = 40 c = lambda test test d = 11.23455
template<typename U, typename ...Ts> voidtprintf(int i, U u, Ts... ts) { auto t = [i, ts...](){ //lambda 捕获参数包 tprintf(i + 1, ts...); }; std::cout <<"i = "<<i<<" value is " << u << std::endl; t(); return ; }
1: lambda1 2: lambda2 3: lambda3 sort: id = 5 name = sort sort: id = 4 name = sortsort sort: id = 15 name = sortsortsort sort: id = 2 name = sortsortsortsort sort: id = 7 name = sortsortsortsortsort