-
Notifications
You must be signed in to change notification settings - Fork 4
/
max_max.cpp
36 lines (30 loc) · 893 Bytes
/
max_max.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
// Finds the largest and second largest values in a range
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <list>
template <typename Iterator>
auto max_max(Iterator begin, Iterator end) {
assert(std::distance(begin, end) >= 2);
using T = typename std::iterator_traits<Iterator>::value_type;
auto it = std::next(begin);
std::pair<T, T> max = std::minmax(*begin, *it);
while (++it != end) {
if (*it > max.first) {
if (*it > max.second) {
max.first = max.second;
max.second = *it;
} else {
max.first = *it;
}
}
}
return max;
}
int main() {
std::list<int> v{10, -2, 15, 1, 204, -10, 17};
auto result = max_max(std::begin(v), std::end(v));
std::cout << result.first << ' ' << result.second;
}