-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay55.cc
More file actions
43 lines (33 loc) · 769 Bytes
/
Day55.cc
File metadata and controls
43 lines (33 loc) · 769 Bytes
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
/*
What will this code print out?
```
def make_functions():
flist = []
for i in [1, 2, 3]:
def print_i():
print(i)
flist.append(print_i)
return flist
functions = make_functions()
for f in functions:
f()
```
How can we make it print out what we apparently want?
*/
#include <bits/stdc++.h>
using namespace std;
vector<function<void()>> make_functions() {
vector<function<void()>> flist;
for (int i : {1, 2, 3}) {
flist.push_back([&]() { cout << i << endl; }); // Output: 3 3 3
// flist.push_back([i]() { cout << i << endl; }); // Output: 1 2 3
}
return flist;
}
int main() {
auto functions = make_functions();
for (auto& f : functions) {
f();
}
return 0;
}