1.匿名函数的作用
相较于普通非匿名函数,匿名函数无需进行另外的声明和定义,仅当调用该匿名时,函数体才会创建,且调用完毕后会立即释放资源。因此匿名函数会更加节省空间,常用于像std::sort这样可以重写排序方式的函数。
2.匿名函数的例子
//例子1:
auto testReturn = [](int a1, int a2) {return a1>a2 };
bool flag = testReturn(23, 21);
cout<<flag<<endl;
//例子2:
int as = 100;
auto testReturn = [](int a1, int a2) {return a1>a2 };
bool flag = testReturn(as, 21);
cout<<flag<<endl;
//例子3:
int as = 100;
auto testReturn = [&](int a1, int a2) {a1 = 10; return a1>a2 };
bool flag = testReturn(as, 21);
cout<<flag<<" "<<as<<endl;
输出结果:
例子1: true
例子2: true
例子3: false 10
3.匿名函数的使用
如上述例子,可以知道匿名函数的格式为 :
[ ] (传入参数) { 函数体 }
[ ] (传入参数)->return-type { 函数体 }
(1) [ ]或是[ = ]可表示传入的参数是值传递,[&]则表示传入的参数是隐式引用传递。
(2) 若在()内表明参数传入方式,则[ ]内声明将失效。
(3) 当函数体内有return或无返回值,->return-type可省略(一般也不会写)。