-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathstl_12_minmax_element.cpp
118 lines (100 loc) · 2.42 KB
/
stl_12_minmax_element.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// code_report
// https://youtu.be/BN9lYrtZsVM
#include <vector>
#include <iostream>
#include <algorithm>
#include <tuple>
#include <iostream>
using namespace std;
void example1_trivial() {
cout << "Min of 1 and 2: " << min(1, 2) << endl;
cout << "Max of 1 and 2: " << max(1, 2) << endl;
}
void example1() {
auto i = { 1, 2, 3 }; // initializer list
cout << "Min is " << min(i) << endl;
cout << "Max is " << max(i) << endl;
}
void example2a() {
// Before C++11
int a = 2;
int b = 1;
pair<int, int> p = minmax(a, b);
cout << "Min is " << p.first << endl;
cout << "Max is " << p.second << endl;
}
void example2b() {
// C++11
int a = 2;
int b = 1;
auto p = minmax(a, b);
cout << "Min is " << p.first << endl;
cout << "Max is " << p.second << endl;
}
void example2c() {
// C++11
int a = 2;
int b = 1;
tie(a, b) = minmax(a, b); // BUG
cout << "Min is " << a << endl;
cout << "Max is " << b << endl;
}
template<typename T>
auto minmax_copy(const T& a, const T& b) {
return (b < a) ? std::pair<const T, const T>(b, a)
: std::pair<const T, const T>(a, b);
}
void example2d() {
// C++11
int a = 2;
int b = 1;
tie(a, b) = minmax_copy(a, b);
cout << "Min is " << a << endl;
cout << "Max is " << b << endl;
}
void example2e() {
// C++17 Structured Bindings
int a = 2;
int b = 1;
auto [min_, max_] = minmax(a, b);
cout << "Min is " << min_ << endl;
cout << "Max is " << max_ << endl;
// min_ = 0; // compile error: assignment of read-only reference ‘min_’
}
void example2f() {
// C++17 Structured Bindings
auto i = { 1, 2, 3 };
auto [min_, max_] = minmax(i);
cout << "Min is " << min_ << endl;
cout << "Max is " << max_ << endl;
}
void example3() {
vector<int> v = { 3, 1, 5, 4, 2 };
auto min_ = *min_element(begin(v), end(v));
cout << "Min is " << min_ << endl;
}
void example4() {
vector<int> v = { 3, 1, 5, 4, 2 };
auto max_ = *max_element(begin(v), end(v));
cout << "Max is " << max_ << endl;
}
void example5() {
vector<int> v = { 3, 1, 5, 4, 2 };
auto[min_, max_] = minmax_element(begin(v), end(v));
cout << "Min is " << *min_ << endl;
cout << "Max is " << *max_ << endl;
}
int main() {
example1_trivial();
example1();
example2a();
example2b();
example2c();
example2d();
example2e();
example2f();
example3();
example4();
example5();
return 0;
}