-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathExercises_16_Generic_Lambdas.cpp
More file actions
88 lines (69 loc) · 2.47 KB
/
Copy pathExercises_16_Generic_Lambdas.cpp
File metadata and controls
88 lines (69 loc) · 2.47 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
// =====================================================================================
// Exercises_16_Generic_Lambdas.cpp
// =====================================================================================
module modern_cpp_exercises:generic_lambdas;
import std;
namespace Exercises_Generic_Lambdas {
namespace Exercise_01 {
static void testExercise_01_01() {
// define a generic lambda
auto isGreaterThanFifty = [](const auto& n) { return n > 50; };
std::vector<int> intValues{ 44, 65, 22, 77, 2 };
// use generic lambda with a vector of integers
auto pos = std::find_if(
std::begin(intValues),
std::end(intValues),
isGreaterThanFifty
);
if (pos != std::end(intValues)) {
std::cout << "Found a value: " << *pos << std::endl;
}
}
class Person
{
private:
std::string m_name;
std::size_t m_age;
public:
Person(const std::string& name, std::size_t age)
: m_name{ name }, m_age{ age } {}
const std::string& getName() const { return m_name; }
bool operator > (std::size_t age) const {
return m_age > age;
}
};
static void testExercise_01_02()
{
// generic lambda - same as above
auto isGreaterThanFifty = [](const auto& object) {
return object > 50;
};
std::vector<Person> personValues{
Person{ "Hans", 40 },
Person{ "Sepp", 60 }
};
// use generic lambda with a vector of Persons
auto pos = std::find_if(
std::begin(personValues),
std::end(personValues),
isGreaterThanFifty
);
if (pos != std::end(personValues)) {
std::cout << "Found Person: " << (*pos).getName() << std::endl;
}
}
static void testExercise()
{
testExercise_01_01();
testExercise_01_02();
}
}
}
void test_exercises_generic_lambdas()
{
using namespace Exercises_Generic_Lambdas;
Exercise_01::testExercise();
}
// =====================================================================================
// End-of-File
// =====================================================================================