lower_bound()和upper_bound()用法详解

lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。

lower_bound( begin,end,num):从数组的begin位置到end-1位置之间二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end地址。用返回的地址减去起始地址begin,可以得到找到的数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end地址。用返回的地址减去起始地址begin,可以得到找到的数字在数组中的下标。

例1

#include<iostream>
#include<algorithm> using namespace std; int main() { const int n = 6; int a[n] = {1,2,4,7,15,34}; sort(a, a + n); cout << "a[0]的地址是:" << a << endl; cout << "a中第一个大于或等于7的元素的地址是:" << lower_bound(a, a + n, 7) << endl; //按从小到大排序 int pos1=lower_bound(a, a + n, 7) - a; //返回数组中第一个大于或等于被查数的值 cout << pos1 << " " << a[pos1] << endl; cout << "a中第一个大于7的元素的地址是:" << upper_bound(a, a + n, 7) << endl; int pos2=upper_bound(a, a + n, 7) - a; //返回数组中第一个大于被查数的值 cout << pos2 << " " << a[pos2] << endl; return 0; } 

运行结果:

a[0]的地址是:0x6efecc
a中第一个大于或等于7的元素的地址是:0x6efed8 3 7 a中第一个大于7的元素的地址是:0x6efedc 4 15 

lower_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end地址。用返回的地址减去起始地址begin,可以得到找到的数字在数组中的下标。
upper_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end地址。用返回的地址减去起始地址begin,可以得到找到的数字在数组中的下标。

例2

#include<iostream>
#include<algorithm> using namespace std; int cmd(int a,int b) { return a>b; } int main() { int num[6]={1,2,4,7,15,34}; //按从小到大排序 sort(num,num+6,cmd); //按从大到小排序 int pos3=lower_bound(num,num+6,7,greater<int>())-num; //返回数组中第一个小于或等于被查数的值 int pos4=upper_bound(num,num+6,7,greater<int>())-num; //返回数组中第一个小于被查数的值 cout<<pos3<<" "<<num[pos3]<<endl; cout<<pos4<<" "<<num[pos4]<<endl; return 0; } 

运行结果:

2 7
3 4

说明,结果中的下标2和3,是相对排序后的数组{34, 15, 7, 4, 2, 1}而言的。

猜你喜欢

转载自www.cnblogs.com/alan-blog-TsingHua/p/10867085.html