-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_capturing_by_reference.cpp
More file actions
64 lines (54 loc) · 1.34 KB
/
lambda_capturing_by_reference.cpp
File metadata and controls
64 lines (54 loc) · 1.34 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
//
// Created by zing on 6/29/2020.
//
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
auto main() -> int {
cout << "[lambda_capturing_by_reference.cpp]" << endl;
// Initializing a vector containing integer element
vector<int> vect;
vect.reserve(10);
for (int i = 0; i < 10; ++i)
vect.push_back(i);
// Displaying the elements of vect
cout << "Original Data:" << endl;
for_each(
begin(vect),
end(vect),
[](int n) {
cout << n << " ";
});
cout << endl;
// Initializing two variables
int a = 1;
int b = 1;
// Capturing value from the two variables
// and mutate them
for_each(
begin(vect),
end(vect),
[&a, &b](int &x) {
const int old = x;
x *= 2;
a = b;
b = old;
});
// Displaying the elements of vect
cout << "Squared Data:" << endl;
for_each(
begin(vect),
end(vect),
[](int n) {
cout << n << " ";
});
cout << endl << endl;
// Displaying value of variable a and b
cout << "a = " << a << endl;
cout << "b = " << b << endl;
[]() {
cout << "=========" << endl;
}();
return 0;
}