-
Notifications
You must be signed in to change notification settings - Fork 0
/
CustomCompareLambda.cpp
executable file
·75 lines (65 loc) · 1.77 KB
/
CustomCompareLambda.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// http://stackoverflow.com/questions/38422886/differences-between-various-custom-comparator-functions-in-c
// Use const reference
// Also make it a friend to have access to private members
struct Student
{
string name;
uint32_t age;
// Method 1: Using operator <
// Making it a friend require two Arguments
//bool operator<(const Student& ob)
friend bool operator<(const Student& ls, const Student& rs)
{
return ls.age < rs.age;
}
};
// Method 2: Custom Compare Function
bool compStudent(const Student& a, const Student& b)
{
return a.age < b.age;
}
// Method 3: Using operator ()
struct MyStudComp
{
bool operator() (const Student& a, const Student& b)
{
return a.age < b.age;
}
}obComp;
void printStudents(vector<Student> studs)
{
for (auto ob : studs)
{
cout << "Name: " << ob.name << "; Age: " << ob.age << endl;
}
cout << endl;
}
int main()
{
vector<Student> studs = {{"abc", 20},
{"def", 14},
{"ghi", 15},
{"jkl", 18},
{"mno", 16},
{"pqr", 12},
{"stu", 11},
{"efg", 13},
{"lmn", 19},
{"cde", 17}};
//sort(studs.begin(), studs.end(), compStudent);
//sort(studs.begin(), studs.end());
sort(studs.begin(), studs.end(), obComp);
// Using Lambda
/*
sort(studs.begin(), studs.end(),
[](const Student& a, const Student& b) -> bool
{
return a.age < b.age;
});
*/
printStudents(studs);
}