C/C++-STL中lower_bound与upper_bound的用法

lower_bound():

 

头文件: #include<algorithm>

函数模板: 如 binary_search()

函数功能:  函数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的位置是越界的!!~

返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置

 

 

upper_bound():

 

头文件:#include<algorithm>

函数模板: 如binary_search()

函数功能:函数upper_bound()返回的在前闭后开区间查找的关键字的上界,返回大于val的第一个元素位置

 

例如:一个数组number序列1,2,2,4.upper_bound(2)后,返回的位置是3(下标)也就是4所在的位置,同样,如果插入元素大于数组中全部元素,返回的是last。(注意:数组下标越界)

返回查找元素的最后一个可安插位置,也就是“元素值>查找值”的第一个元素的位置

 

注意:

         lower_bound(val):返回容器中第一个值【大于或等于】val的元素的iterator位置。

        upper_bound(val): 返回容器中第一个值【大于】val的元素的iterator位置。

 

不加比较函数的情况:

[cpp]  view plain  copy
  1. int a[]={0,1,2,2,3};  
  2. printf("%d\n",lower_bound(a,a+5,2,cmp)-a);  
  3. 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号位置

加了比较函数:

[cpp]  view plain  copy
  1. bool cmp(int a,int b)  
  2. {  
  3.     return a<b;  
  4. }  
  5. int main()  
  6. {  
  7.     int a[]={0,1,2,2,3};  
  8.     printf("%d\n",lower_bound(a,a+5,2,cmp)-a);  
  9.     printf("%d\n",upper_bound(a,a+5,2,cmp)-a);  
  10.     return 0 ;  
  11. }  

结果仍然是2 4 ,可以得出一个结论, cmp里函数应该写的是小于运算的比较

如果加上了等号,lower和upper两个函数功能就刚好反过来了:

[cpp]  view plain  copy
  1. bool cmp(int a,int b)  
  2. {  
  3.     return a<=b;  
  4. }  
  5. int main()  
  6. {  
  7.     int a[]={0,1,2,2,3};  
  8.     printf("%d\n",lower_bound(a,a+5,2,cmp)-a);  
  9.     printf("%d\n",upper_bound(a,a+5,2,cmp)-a);  
  10.     return 0 ;  
  11. }  

结果是4 2

#include <iostream>
#include <algorithm>//必须包含的头文件
using namespace std;
int main()
{
	 int point[10] = {1,3,7,7,9};
	 int tmp = upper_bound(point, point + 5, 7) - point;//按从小到大,7最多能插入数组point的哪个位置
	 	printf("%d\n",tmp);
	 tmp = lower_bound(point, point + 5, 7) - point;按从小到大,7最少能插入数组point的哪个位置
		 printf("%d\n",tmp);
	 return 0;
}
output:
4
2


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值