0
点赞
收藏
分享

微信扫一扫

小朋友学C++(46): 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() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num,greater() ):从数组的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


小朋友学C++(46): lower_bound()和upper_bound()_二分查找


举报

相关推荐

0 条评论