-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemberVariableCapture.cpp
60 lines (47 loc) · 1.2 KB
/
MemberVariableCapture.cpp
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
/**
* \file MemberVariableCapture.cpp
* \brief
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//--------------------------------------------------------------------------------------------------
class OddCounter
{
public:
int getCount()
{
return mCounter;
}
void update(std::vector<int> & vec)
{
// Traverse the vector and increment mCounter if element is odd
// this is captured by value inside lambda
std::for_each(vec.begin(), vec.end(),
[this](int element)
{
if (element % 2) {
// Accessing member variable from outer scope
++ mCounter;
}
});
}
private:
// tracks the count of odd numbers encountered
int mCounter {};
};
//--------------------------------------------------------------------------------------------------
int main(int, char **)
{
std::vector<int> vec = {12,3,2,1,8,9,0,2,3,9,7};
OddCounter counterObj;
// Passing the vector to OddCounter object
counterObj.update(vec);
int count = counterObj.getCount();
std::cout << "Counter = " << count << std::endl;
return EXIT_SUCCESS;
}
//--------------------------------------------------------------------------------------------------
#if OUTPUT
Counter = 6
#endif