Repository navigation
Expand file tree
/
Copy pathfunction_pointers.cpp
More file actions
88 lines (69 loc) · 2.6 KB
/
Copy pathfunction_pointers.cpp
File metadata and controls
88 lines (69 loc) · 2.6 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
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
// 1. Обычные функции
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
// 2. Callback
int calculate(int a, int b, int (*operation)(int, int)) {
return operation(a, b);
}
// 3. std::function
int calculateFunc(int a, int b, function<int(int, int)> operation) {
return operation(a, b);
}
int main() {
cout << "=== Урок 21: Указатели на функции ===\n\n";
// 1. Указатель на функцию
cout << "1. Указатель на функцию\n";
int (*funcPtr)(int, int);
funcPtr = add;
cout << "funcPtr(5, 3) = " << funcPtr(5, 3) << " (add)\n";
funcPtr = subtract;
cout << "funcPtr(5, 3) = " << funcPtr(5, 3) << " (subtract)\n";
funcPtr = multiply;
cout << "funcPtr(5, 3) = " << funcPtr(5, 3) << " (multiply)\n\n";
// 2. Callback
cout << "2. Callback\n";
cout << "calculate(10, 5, add) = " << calculate(10, 5, add) << endl;
cout << "calculate(10, 5, subtract) = " << calculate(10, 5, subtract) << "\n\n";
// 3. std::function
cout << "3. std::function\n";
function<int(int, int)> op = add;
cout << "op(10, 5) = " << op(10, 5) << endl;
op = multiply;
cout << "op(10, 5) = " << op(10, 5) << " (после op = multiply)\n\n";
// 4. Лямбда
cout << "4. Лямбда-функции\n";
auto square = [](int x) { return x * x; };
cout << "square(5) = " << square(5) << endl;
cout << "Лямбда как callback: "
<< calculateFunc(10, 5, [](int a, int b) { return a * b; }) << "\n\n";
// 5. Лямбды в STL
cout << "5. Лямбды в sort\n";
vector<int> nums = {5, 2, 8, 1, 9};
cout << "До: ";
for (int x : nums) cout << x << " ";
cout << endl;
sort(nums.begin(), nums.end(), [](int a, int b) {
return a > b;
});
cout << "После сортировки (убывание): ";
for (int x : nums) cout << x << " ";
cout << "\n\n";
// 6. Калькулятор
cout << "6. Калькулятор\n";
int a = 12, b = 4;
cout << a << " + " << b << " = " << calculate(a, b, add) << endl;
cout << a << " - " << b << " = " << calculate(a, b, subtract) << endl;
cout << a << " * " << b << " = " << calculate(a, b, multiply) << endl;
auto divide = [](int x, int y) {
if (y == 0) return 0;
return x / y;
};
cout << a << " / " << b << " = " << calculateFunc(a, b, divide) << "\n";
return 0;
}