1.简介
中文名匿名函数
lambda的存在可以让你在函数里面写函数
其形式为
[](){}
一个简单的例子
下面是一个不可以使用外部变量,没有确切返回类型的lambda表达式用在了sort里代替了cmp()
sort(points.begin(), points.end(), [](Point a, Point b) {
return a.y < b.y;
});
下面是一个有名字的可以使用外部变量的有明确返回类型的lambda表达式
bool ok = false;
auto fun = [&](vector<int> &nums) -> void {
nums.clear();
ok = true;
};
2.参数类型
[]
部分为要捕获的外部变量
我们只需要简单的知道
-
[&] 可以使用和修改
-
[=] 可以使用但不可以修改
-
[] 不可以使用
()
为labmda参数,实际相当于函数参数
{}
相当于函数正文
除此之外
auto fun1 = []() -> int {};
auto fun2 = []() -> bool {};
可以指定函数返回类型
3.在ACM中的使用
1)在sort()中代替cmp函数或者重载运算符
对于需要多次按不同规则的排序很好用
sort(points.begin(), points.end(), [](array<int, 3> a, array<int, 3> b) {
return a[2] < b[2];
});
2)和function结合写函数内的函数
void solution()
{
cin >> n;
queue<int> Q;
M.clear();
int tot = 0;
int cnt = 0;
ok = true;
for (int i = 1; i <= n; i++)
{
int tmp;
cin >> tmp;
tot += tmp;
M[tmp]++;
}
function<void(int)> dfs = [&](int nowNum) -> void {
if (!ok)
return;
if (M[nowNum])
{
M[nowNum]--;
return;
}
if (nowNum >= 2)
{
dfs(nowNum / 2);
dfs((nowNum + 1) / 2);
}
else
ok = false;
};
dfs(tot);
for (auto it : M)
if (it.second)
ok = false;
if (ok)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
这里需要注意的是,类型不能再写成auto,需要指定函数类型
function<type1(type2,type3)> fun = [](type2 arg1,type3 arg2){};
// 相当于
type1 fun(type2 arg1, type3 arg2) {};