-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemplated-sort.cpp
More file actions
76 lines (55 loc) · 2.22 KB
/
templated-sort.cpp
File metadata and controls
76 lines (55 loc) · 2.22 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
#include <iostream>
#include <algorithm>
template<typename TRandomAccessIterator, typename TPredicate>
void customSort(
TRandomAccessIterator first, TRandomAccessIterator last,
TPredicate predicate) {
/// Здесь должен быть ваш код -- сортировка пузырьковая или слиянием
std::sort(first, last, predicate);
}
template<typename TIterator>
void printRange(TIterator first, TIterator last) {
int counter = 0;
for ( ; first != last; ++first) {
std::cout << *first << " ";
if (++counter > 100) {
std::cout << "and so on ...";
break;
}
}
std::cout << std::endl;
}
template<typename T> bool customLess(const T& a, const T& b) { return a < b; }
template<typename T>
struct RuntimeLess {
/// Ответ будет зависеть от флага, выставляемого в момент исполнения программы
bool inverse = false;
bool operator()(const T& a, const T& b) const {
return inverse ? (a < b) : (a > b);
}
};
int main() {
const size_t N = 10;
std::vector<int> stdvec(N);
srand(time(0));
for (int& i : stdvec) { i = rand() % N; }
printRange(stdvec.begin(), stdvec.end());
/// Благодаря шаблонизации возможны любые вызовы нашей функции,
/// перечисленные ниже -- лишь бы при генерации и сборке компилятором
/// обычного кода из нашего шаблонного кода не возникало ошибок
customSort(stdvec.begin(), stdvec.end(), customLess<int>);
customSort(stdvec.begin(), stdvec.end(), RuntimeLess<int>());
RuntimeLess<int> runtimeLess;
customSort(stdvec.begin(), stdvec.end(), runtimeLess);
printRange(stdvec.begin(), stdvec.end());
runtimeLess.inverse = true;
customSort(stdvec.begin(), stdvec.end(), runtimeLess);
printRange(stdvec.begin(), stdvec.end());
customSort(stdvec.begin(), stdvec.end(), std::greater<int>());
printRange(stdvec.begin(), stdvec.end());
customSort(stdvec.begin(), stdvec.end(), std::less<int>());
printRange(stdvec.begin(), stdvec.end());
customSort(stdvec.begin(), stdvec.end(),
[](const int& a, const int& b) { return a < b; });
return 0;
}