ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置。
ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法返回一个非递减序列[first, last)中第一个大于val的位置。
http://blog.csdn.net/niushuai666/article/details/6734403
函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置
举例如下:
一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标
则
pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。
pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。
pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。
所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~
返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置
测试代码如下:
- #include <iostream>
- #include <algorithm>
- #include <functional>
- #include <vector>
-
- using namespace std;
-
-
- int main()
- {
- const int VECTOR_SIZE = 8 ;
-
-
- typedef vector<int > IntVector ;
-
-
- typedef IntVector::iterator IntVectorIt ;
-
- IntVector Numbers(VECTOR_SIZE) ;
-
- IntVectorIt start, end, it, location ;
-
-
- Numbers[0] = 4 ;
- Numbers[1] = 10;
- Numbers[2] = 11 ;
- Numbers[3] = 30 ;
- Numbers[4] = 69 ;
- Numbers[5] = 70 ;
- Numbers[6] = 96 ;
- Numbers[7] = 100;
-
- start = Numbers.begin() ;
-
-
- end = Numbers.end() ;
-
-
-
- cout << "Numbers { " ;
- for(it = start; it != end; it++)
- cout << *it << " " ;
- cout << " }\n" << endl ;
-
-
-
- location = lower_bound(start, end, 1) ;
-
- cout << "First location element 10 can be inserted in Numbers is: "
- << location - start<< endl ;
- }
调用lower_bound之前必须确定序列为有序序列,否则调用出错。第一个版本排序根据底层的 <(小于)操作符,第二个版本根据comp进行排序。
http://blog.csdn.net/tjpuacm/article/details/26389441
不加比较函数的情况:
- int a[]={0,1,2,2,3};
- printf("%d\n",lower_bound(a,a+5,2,cmp)-a);
- printf("%d\n",upper_bound(a,a+5,2,cmp)-a);
结果:2 4
lower的意义是对于给定的已经排好序的a,key最早能插入到那个位置
0 1 | 2 2 3 所以2最早插入到2号位置
upper的意义是对于给定的已经排好序的a,key最晚能插入到那个位置
0 1 2 2 | 3 所以2最晚插入到4号位置
加了比较函数:
- bool cmp(int a,int b)
- {
- return a<b;
- }
- int main()
- {
- int a[]={0,1,2,2,3};
- printf("%d\n",lower_bound(a,a+5,2,cmp)-a);
- printf("%d\n",upper_bound(a,a+5,2,cmp)-a);
- return 0 ;
- }
结果仍然是2 4 ,可以得出一个结论,
cmp里函数应该写的是小于运算的比较
如果加上了等号,lower和upper两个函数功能就刚好反过来了:
- bool cmp(int a,int b)
- {
- return a<=b;
- }
- int main()
- {
- int a[]={0,1,2,2,3};
- printf("%d\n",lower_bound(a,a+5,2,cmp)-a);
- printf("%d\n",upper_bound(a,a+5,2,cmp)-a);
- return 0 ;
- }
结果是4 2