所在头文件:#include<algorithm>
函数分类:Binary search (operating on partitioned/sorted ranges)
函数功能:lower_bound()返回一个迭代器指针,指向val出现在这个被查找序列中出现的第一个位置;upper_bound()返回一个迭代器指针,指向val出现在这个被查找序列中出现的最后一个位置的后一个位置。
lower_bound()的函数模板功能相当于:
template <class ForwardIterator, class T> ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val) { ForwardIterator it; iterator_traits<ForwardIterator>::difference_type count, step; count = distance(first,last); while (count>0) { it = first; step=count/2; advance (it,step); if (*it<val) { // or: if (comp(*it,val)), for version (2) first=++it; count-=step+1; } else count=step; } return first; }
upper_bound()的函数模板功能相当于:
<pre name="code" class="cpp">template <class ForwardIterator, class T> ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val) { ForwardIterator it; 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)) // or: if (!comp(val,*it)), for version (2) { first=++it; count-=step+1; } else count=step; } return first; }
函数模板:
#include <bits/stdc++.h> using namespace std; int lower(int *array, int b, int e, int val) { int first = b; int count = e - b; while (count > 0) { int it = first; int step = count / 2; it = it + step; if (array[it] < val) { first = ++it; count = count - (step + 1); } else { count = step; } } return first; } int upper(int *array, int b, int e, int val) { int first = b; int count = e - b; while (count > 0) { int it = first; int step = count / 2; it = it + step; if (array[it] <= val) { first = ++it; count = count - (step + 1); } else { count = step; } } return first; } int main() { int array[] = {0,1,2,3,4,5,5,5,5,5,6,6,6,7,8,9,10,11,11,11,12,12,13,13}; int e = sizeof(array) / sizeof(int); int ans1 = lower(array, 0, e - 1, 11); int ans2 = upper(array, 0, e - 1, 11); printf("%d\n", ans1); printf("%d\n", ans2); printf("-------------\n"); int ans3 = lower(array, 0, e - 1, 13); int ans4 = upper(array, 0, e - 1, 13); printf("%d\n", ans3); printf("%d\n", ans4); printf("-------------\n"); int ans5 = lower(array, 0, e - 1, 100); int ans6 = upper(array, 0, e - 1, 100); printf("%d\n", ans5); printf("%d\n", ans6); printf("-------------\n"); return 0; }