Lambda expressions (since C++11)
Syntax
[ captures ] <tparams>(optional)(c++20) ( params ) specifiers(optional) exception attr -> ret { body } |
(1) | ||||||||
[ captures ] ( params ) -> ret { body } |
(2) | ||||||||
[ captures ] ( params ) { body } |
(3) | ||||||||
[ captures ] { body } |
(4) | ||||||||
上代码:
1 // lambdaprj.cpp : Defines the entry point for the console application.
2 //
3
4 #include "stdafx.h"
5 #include<algorithm>
6 #include<vector>
7 #include<iostream>
8 #include<functional>
9 using namespace std;
10
11 /*
12 * []()->{};
13 * [ capture list] ( params list) mutable exception attribute -> ret { body }
14 */
15 int main()
16 {
17 auto sayHelloWorld = []() {
18 cout << "hello world" << endl;
19 };
20 sayHelloWorld();
21 auto add_ = [](int a,int b)->int {
22 return a + b;
23 };
24 cout<< add_(190, 10)<<endl;
25
26 int i = 99;//read only
27 auto add_with_i = [i](int a, int b)->int {
28 return a + b + i;
29 };
30 cout << add_with_i(190,10)<<endl;
31 //
32
33 int j = 100;
34 auto add_with_j_c = [&j](int a, int b)-> int{
35 j = 101;
36 return a + b + j;
37 };
38 cout << add_with_j_c(190, 10) << " j:" << j << endl;
39 //
40
41 vector<int> arr = { 1,2,3,4,5 };
42 int total = 0;
43 for_each(begin(arr), end(arr),
44 [&](int x)->int{
45 return total += x;
46 });
47 cout << "total:" << total << endl;
48 //
49 vector<int> sort_arr = { 2,-1,3,4,6,7,2,31 };
50 cout << "unsort : ";
51 for_each(begin(sort_arr),end(sort_arr),
52 [](int x) {
53 cout << x << " "; });
54 cout << endl;
55 sort(begin(sort_arr),end(sort_arr),
56 [](int a, int b)->bool {
57 return abs(a) < abs(b); });
58 cout << "sort : ";
59 for_each(begin(sort_arr), end(sort_arr),
60 [](int x) {
61 cout << x << " "; });
62 cout << endl;
63 //
64
65 auto func = [](function<void()> f) {
66 f();
67 };
68 int x = 100;
69 auto func_add = [&]() {
70 x++;
71 };
72 func(func_add);
73 cout << "x:" << x << endl;
74 getchar();
75 return 0;
76 }
参考学习: