forked from chronolaw/cpp_study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda.cpp
More file actions
157 lines (123 loc) · 2.02 KB
/
lambda.cpp
File metadata and controls
157 lines (123 loc) · 2.02 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
// Copyright (c) 2020 by Chrono
//
// g++ lambda.cpp -std=c++14 -o a.out;./a.out
// g++ lambda.cpp -std=c++14 -I../common -o a.out;./a.out
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void my_square(int x)
{
cout << x*x << endl;
}
void case1()
{
auto pfunc = &my_square;
(*pfunc)(3);
auto func = [](int x)
{
cout << x*x << endl;
};
func(3);
}
void case2()
{
int n = 10;
auto func = [=](int x)
{
cout << x*n << endl;
};
func(3);
}
void case3()
{
auto f1 = [](){};
auto f2 = []()
{
cout << "lambda f2" << endl;
auto f3 = [](int x)
{
return x*x;
};// lambda f3
cout << f3(10) << endl;
}; // lambda f2
f1();
f2();
//f1 = f2;
vector<int> v = {3, 1, 8, 5, 0};
cout << *find_if(begin(v), end(v),
[](int x)
{
return x >= 5;
}
)
<< endl;
}
void case4()
{
int x = 33;
auto f1 = [=]()
{
//x += 10;
cout << x << endl;
};
auto f2 = [&]()
{
x += 10;
};
auto f3 = [=, &x]()
{
x += 20;
};
f1();
f2();
cout << x << endl;
f3();
cout << x << endl;
}
class DemoLambda final
{
public:
DemoLambda() = default;
~DemoLambda() = default;
private:
int x = 0;
public:
auto print()
{
//auto f = [=]()
return [this]()
{
cout << "member = " << x << endl;
};
}
};
void case5()
{
DemoLambda obj;
auto f = obj.print();
f();
}
void case6()
{
auto f = [](const auto& x)
{
return x + x;
};
cout << f(3) << endl;
cout << f(0.618) << endl;
string str = "matrix";
cout << f(str) << endl;
}
int main()
{
case1();
case2();
case3();
case4();
case5();
case6();
cout << "lambda demo" << endl;
}