-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_capturing_by_value.cpp
More file actions
65 lines (55 loc) · 1.53 KB
/
lambda_capturing_by_value.cpp
File metadata and controls
65 lines (55 loc) · 1.53 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
//
// Created by zing on 6/29/2020.
//
/* lambda_capturing_by_value.cpp */
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
auto main() -> int {
cout << "[lambda_capturing_by_value.cpp]" << endl;
// Initializing a vector containing integer element
vector<int> vect;
//Attempt to preallocate enough memory for specified number of elements.
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 = 2;
int b = 8;
// Capturing value explicitly from the two variables
cout << "Printing elements between " << a;
cout << " and " << b << " explicitly [a,b]:" << endl;
for_each(
begin(vect),
end(vect),
[a, b](int n) {
if (n >= a && n <= b)
cout << n << " ";
});
cout << endl;
// Modifying variable a and b
a = 3;
b = 7;
// Capturing value implicitly from the two variables
cout << "printing elements between " << a;
cout << " and " << b << " implicitly[=]:" << endl;
for_each(
begin(vect),
end(vect),
[=](int n) {
if (n >= a && n <= b)
cout << n << " ";
});
cout << endl;
return 0;
}