声明 Lambda 表达式

1
2
3
4
5
auto f1 = [](int x, int y) { return x + y; };
cout << f1(2, 3) << endl; // 输出 5

function<int(int, int)> f2 = [](int x, int y) { return x + y; };
cout << f2(3, 4) << endl; // 输出 7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <functional>
#include <iostream>

int main()
{
using namespace std;

int i = 3, j = 5;

function<int (void)> f = [i, &j] { return i + j; };

i = 22;
j = 44;

cout << f() << endl; // 3 + j = 47,输出 47
}

调用 Lambda 表达式

1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
using namespace std;
int n = [] (int x, int y) { return x + y; }(5, 4);
cout << n << endl; // 输出 9
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// STL+Lambda 用法
#include <list>
#include <algorithm>
#include <iostream>

int main()
{
using namespace std;

list<int> numbers;
numbers.push_back(13);
numbers.push_back(17);
numbers.push_back(42);
numbers.push_back(46);
numbers.push_back(99);

const list<int>::const_iterator result =
find_if(numbers.begin(), numbers.end(),[](int n) { return (n % 2) == 0; });

if (result != numbers.end()) {
cout << "The first even number in the list is " << *result << "." << endl; // 第一个偶数是 42
} else {
cout << "The list contains no even numbers." << endl;
}
}

嵌套 Lambda 表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
using namespace std;

// The following lambda expression contains a nested lambda
// expression.
int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);

// Print the result.
cout << timestwoplusthree << endl;
}

高阶Lambda函数

https://msdn.microsoft.com/zh-cn/library/dd293599.aspx