C++新增特性 lambda:主要用于函数内部定义,以减少函数,直观展示函数功能作用,只用于简短函数。
函数形式,结构:
[捕获外部变量列表] (形参列表) 指示符 异常设定 返回类型 函数体
[capture list] (params list) mutable exception-> return type { function body }
capture list:捕获外部变量列表
params list:形参列表
mutable指示符:用来说用是否可以修改捕获的变量
exception:异常设定
return type:返回类型
function body:函数体
捕获外部变量的引入符:
[] // 不捕获任何外部变量
[=] // 以值的形式捕获所有外部变量
[&] // 以引用形式捕获所有外部变量
[x, &y] // x 以传值形式捕获,y 以引用形式捕获
[=, &z] // z 以引用形式捕获,其余变量以传值形式捕获
[&, x] // x 以值的形式捕获,其余变量以引用形式捕获
例子1:简单lambda函数,可自动判断返回值类型
#include <algorithm>
#include <cmath>
void abssort(float *x, unsigned N)
{
std::sort(x,
x + N,
//不用外部任何变量[],只用形参传递值,达到封闭效果
[](float a, float b) { return std::abs(a) < std::abs(b); });
}
例子2:引用外部变量修改
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(int argc, char** argv)
{
string s1("Hello World!");
string s2("My God!!!!");
auto func = [&s2](const string ss) {
cout<<"Get string:"<<ss<<endl;
s2[0] = '*';
cout << s2 << endl;
};
func(s1);
}
结果值:
Get string:Hello World!
*y God!!!!
例子3:值传递外部变量(默认以const 形式传入外部变量),需要修改的话,需引入 mutable指示符。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(int argc, char** argv)
{
string s1("Hello World!");
string s2("My God!!!!");
//有mutable 修饰时,前面的形参'()'不能隐藏,要显示写出。
auto func = [s2](const string ss) mutable {
cout<<"Get string:"<<ss<<endl;
s2[0] = '*';
cout << s2 << endl;
};
func(s1);
cout << s2 << endl;
}
结果:
Get string:Hello World!
*y God!!!!
My God!!!!
例子4:以值的形式捕获外部全部变量‘[=]’
#include<string>
using namespace std;
int main(int argc, char** argv)
{
string s1("Hello World!");
string s2("My God!!!!");
auto func = [=](const string ss) mutable {
cout<<"Get string:"<<ss<<endl;
s2[0] = '*';
cout << s2 << endl;
};
func(s1);
cout << s2 << endl;
}
结果:
Get string:Hello World!
*y God!!!!
My God!!!!
例子5:以引用的形式捕获外部全部变量‘[&]’
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(int argc, char** argv)
{
string s1("Hello World!");
string s2("My God!!!!");
auto func = [&](const string ss) mutable {
cout<<"Get string:"<<ss<<endl;
s2[0] = '*';
cout << s2 << endl;
};
func(s1);
cout << s2 << endl;
}
结果:
Get string:Hello World!
*y God!!!!
*y God!!!!
例子6:指定返回值类型‘->int’
#include<iostream>
using namespace std;
int main(int argc, char** argv)
{
auto func = [&]() mutable -> int{
return 1.1;
};
auto res = func();
cout << res << endl;
}
结果:
1
例子7:默认形参值
#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int aaa = 3;
auto func = [](int abc) mutable -> int{
return abc;
}(aaa);//默认形参aaa
auto res = func;
cout << res << endl;
return 0;
}
结果:
3