Lambda 是c++11最重要的特性之一,是函数式编程风格的基石。它实际上是提供了类似匿名函数的特性(简单地说,就是可以在需要的地方定义函数,而不是定义好才能使用)。
Lambda表达式基础
Lambda表达式基础语法
[捕获列表](参数列表) _mutable 异常属性->返回类型_ //下划线内可放空
{
//函数体
}
绿书上的第一个例子
stuct TS
{
int a, b, c;
};
TS tss[1000];
sort(tss, tss + n, [](const TS &t1, const &t2) {
if (t1.a != t2.a)
return t1.a < t2.a;
if (t1.b != t2.b)
return t1.b < t2.b;
return t1.c <= t2.c;
})
上面这个例子中,捕获列表为空 。因为这个函数并没有调用另外的参数。
绿书上的第二个例子
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> list{1, 2, 3};
int total = 0;
for_each(list.begin(), list.end(), [&total](int x) { total += x; });
cout << total;
}
另外,还可以直接像声明一个变量一样声明一个函数
绿书上的第三个例子
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> list{1, 2, 3};
int total = 0;
auto add = [&total](int x) { total += x; };
//类型推导,实际上是std::function<void(int)> add
for_each(list.begin(), list.end(), add);
cout << total;
}