lower_bound()函数返回能够插入value的第一个位置,该函数要求目标序列必须是有序的。
- template <class ForwardIterator, class T>
- inline ForwardIterator lower_bound(ForwardIterator first,
- ForwardIterator last,
- const T &value) {
- return __lower_bound(first, last, value,
- distance_type(first), iterator_category(first));
- }
- // forward iterator 版本
- template <class ForwardIterator, class T, class Distance>
- ForwardIterator __lower_bound(ForwardIterator first,
- ForwardIterator last,
- const T &value,
- Distance*,
- forward_iterator_tag) {
- Distance len = 0;
- distance(first, last, len);
- Distance half;
- ForwardIterator middle;
- while(len > 0) {
- half = len >> 1;
- advance(middle, half);
- if(*middle < value) {
- first = middle;
- ++first;
- len = len - half - 1;
- } else
- len = half;
- }
- return first;
- }
- // random access iterator 版本
- template <class RandomAccessIterator, class T, class Distance>
- RandomAccessIterator __lower_bound(RandomAccessIterator first,
- RandomAccessIterator last,
- const T &value,
- Distance*,
- random_access_iterator_tag) {
- Distance len = last - first;
- Distance half;
- RandomAccessIterator middle;
- while(len > 0) {
- half = len >> 1;
- middle = first + half;
- if(*middle < value) {
- first = middle + 1;
- len = len - half - 1;
- } else
- len = half;
- }
- return first;
- }