1 #include <iostream> 2 #include <array> 3 using namespace std; 4 5 //解决函数怀孕现象 6 //[](){} 7 //[] =引用,只读 =mutable读原本改副本 &读写原本 //&a,b a可读写,b只能读 8 //() 参数,int a,int b 9 //{}语句 10 void main() 11 { 12 //lambda表达式 13 auto fun1 = [] {cout << "hello" << endl; cout << "hello2" << endl; };//函数指针 14 fun1();//括号起到调用的作用 15 16 //[](参数列表){执行逻辑} 17 auto fun2 = [](char *str) {cout << str << endl; }; 18 fun2("hello3"); 19 20 //lambda带参函数 21 auto fun3 = [](int a, int b) {return a + b; }; 22 cout << fun3(10, 19) << endl; 23 24 //->用在(){}之间,用于确定返回值类型 25 auto fun4 = [](int a, int b)->double {return a + b; }; 26 cout << fun4(10, 19) << endl; 27 28 //decltype解决类型自动推理 29 auto fun5 = [](int a, int b)->decltype(a+b) {return a + b; }; 30 cout << fun5(10, 19) << endl; 31 32 int num1 = 20; 33 int num2 = 33; 34 //=可以使用外部变量,只能读不能写 35 auto fun6 = [=](){cout << num1 << num2 << endl; }; 36 fun6(); 37 38 //&可以使用外部变量,读写(对原数据的操作) 39 auto fun7 = [&](){num1 = 1; cout << num1 << num2 << endl; }; 40 fun7(); 41 42 //mutable可以使用外部变量,读写(副本机制,不对原数据进行改变) 43 auto fun8 = [=]()mutable{num1 = 1; cout << num1 << num2 << endl; }; 44 fun8(); 45 46 //指定可读写的元素 num1可读可写,num2只能读 47 auto fun9 = [&num1, num2]() {num1 = 30; cout << num2 << endl; }; 48 fun9(); 49 50 //mutable可读可写但作用的是副本 51 auto fun10 = [num1, num2]() mutable{num1 = 30; cout << num2 << endl; }; 52 fun10(); 53 54 //lambda与auto 55 auto fun11 = [](auto a, auto b)->decltype(a+b){return a + b; }; 56 cout << fun11(1,3.9) << endl; 57 58 //内嵌调用lambda 59 array<int, 10> myarray{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; 60 for_each(myarray.begin(), myarray.end(), [](int &num) {num += 1; cout << num << endl; }); 61 cin.get(); 62 }