-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionPointer.cpp
More file actions
61 lines (47 loc) · 1.15 KB
/
Copy pathFunctionPointer.cpp
File metadata and controls
61 lines (47 loc) · 1.15 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
#include <algorithm>
#include <iostream>
#include <vector>
namespace {
int increase(int a, int b) {
return a > b;
}
int decrease(int a, int b) {
return a < b;
}
// // Function
// // Declaring
// return_type (*FuncPtr) (parameter type, ....);
typedef int (*SortFcn)(int a, int b);
void run() {
std::vector<int> vect{1, 6, 4, 22, 0, 6, 33, 39, -5};
auto f_print = [](const std::vector<int>& vec) {
for (const auto& e : vec) {
std::cout << e << " ";
}
std::cout << "\n";
};
std::cout << "Before sorting : \n";
f_print(vect);
std::cout << "Sorting in descending "
<< "order \n";
// Use auto
auto sortTypeAuto = increase;
std::sort(vect.begin(), vect.end(), sortTypeAuto);
// Use pointer
SortFcn sortTypePtr = decrease;
f_print(vect);
std::cout << "Sorting with absolute "
<< "value as parameter\n ";
std::sort(vect.begin(), vect.end(), sortTypePtr);
for (auto i : vect)
std::cout << i << " ";
std::cout << "\n";
}
} // namespace
struct FunctionPointer {
FunctionPointer() {
std::cout << "\n--- Function Pointer Example ---\n";
run();
}
};
static FunctionPointer autoRunner;