-
Notifications
You must be signed in to change notification settings - Fork 3
/
Algorithm.h
90 lines (83 loc) · 1.76 KB
/
Algorithm.h
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
/*
Algorithm.h
*/
#ifndef ALGORITHM_H_
#define ALGORITHM_H_
#include <algorithm>
namespace ha
{
// 对所有元素进行条件测试
template<typename InputIterator, typename UnaryPredicate>
bool all_of(InputIterator first, InputIterator last,
UnaryPredicate pred)
{
while (first != end)
{
if (!(pred(*first)))
{
return false;
}
++first;
}
return true;
}
// 二分查找序列中第一个比val大的元素所对应的迭代器
template<typename ForwardIterator, typename T>
ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last,
const T& val)
{
ForwardIterator it;
std::iterator_traits<ForwardIterator>::difference_type count, step;
count = std::distance(first, last);
while (count > 0)
{
it = first;
step = count / 2;
std::advance(it, step);
if (!(val < *it))
{
first = ++it;
count -= step + 1;
}
else
{
count = step;
}
}
return first;
}
// 二分法查找序列中第一个大于等于val值的元素所对应的指针
template<typename ForwardIterator, typename T>
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last,
const T& val)
{
ForwardIterator it;
std::iterator_traits<ForwardIterator>::difference_type count, step;
count = std::distance(first, last);
while (count > 0)
{
it = first;
step = count / 2;
std::advance(it, step);
if (val > *it)
{
first = ++it;
count -= step + 1;
}
else
{
count = step;
}
}
return first;
}
// 二分搜索
template<typename ForwardIterator, typename T>
bool binary_search(ForwardIterator first, ForwardIterator last,
const T& val)
{
first = std::lower_bound(first, last, val);
return (first != last && *first == val);
}
}
#endif