1+ /*
2+ Algorithm.h
3+
4+ */
5+
6+ #ifndef ALGORITHM_H_
7+ #define ALGORITHM_H_
8+
9+ #include < algorithm>
10+
11+ namespace ha
12+ {
13+ // 对所有元素进行条件测试
14+ template <typename InputIterator, typename UnaryPredicate>
15+ bool all_of (InputIterator first, InputIterator last,
16+ UnaryPredicate pred)
17+ {
18+ while (first != end)
19+ {
20+ if (!(pred (*first)))
21+ {
22+ return false ;
23+ }
24+ ++first;
25+ }
26+ return true ;
27+ }
28+
29+ // 二分查找序列中第一个比val大的元素所对应的迭代器
30+ template <typename ForwardIterator, typename T>
31+ ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,
32+ const T& val)
33+ {
34+ ForwardIterator it;
35+ std::iterator_traits<ForwardIterator>::difference_type count, step;
36+ count = std::distance (first, last);
37+ while (count > 0 )
38+ {
39+ it = first;
40+ step = count / 2 ;
41+ std::advance (it, step);
42+ if (!(val < *it))
43+ {
44+ first = ++it;
45+ count -= step + 1 ;
46+ }
47+ else
48+ {
49+ count = step;
50+ }
51+ }
52+ return first;
53+ }
54+
55+ // 二分法查找序列中第一个大于等于val值的元素所对应的指针
56+ template <typename ForwardIterator, typename T>
57+ ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,
58+ const T& val)
59+ {
60+ ForwardIterator it;
61+ std::iterator_traits<ForwardIterator>::difference_type count, step;
62+ count = std::distance (first, last);
63+ while (count > 0 )
64+ {
65+ it = first;
66+ step = count / 2 ;
67+ std::advance (it, step);
68+ if (val > *it)
69+ {
70+ first = ++it;
71+ count -= step + 1 ;
72+ }
73+ else
74+ {
75+ count = step;
76+ }
77+ }
78+ return first;
79+ }
80+
81+ // 二分搜索
82+ template <typename ForwardIterator, typename T>
83+ bool binary_search (ForwardIterator first, ForwardIterator last,
84+ const T& val)
85+ {
86+ first = std::lower_bound (first, last, val);
87+ return (first != last && *first == val);
88+ }
89+ }
90+ #endif
0 commit comments