lower_bound( )和upper_bound( )

lower_bound()和upper_bound()都是利用二分查找的方法在一个排好序的数组中进行查找的。需要引入头文件:algorithm。
1)在从小到大的排序数组中
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
2)在从大到小的排序数组中
lower_bound(begin,end,num,greater()):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound(begin,end,num,greater()):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

#include<iostream>
#include<algorithm>
using namespace std;

void print(int a[],int n)
{
	for(int i=0;i<n;i++)
		cout<<a[i]<<" ";
	cout<<endl;
}
int main()
{
	int a[6]={6,2,7,4,20,15}; 
	sort(a,a+6);  //按从小到大排序 
	print(a,6); 
	int pos1=lower_bound(a,a+6,7)-a; //返回数组中第一个大于或等于7的下标 
	int pos2=upper_bound(a,a+6,7)-a; //返回数组中第一个大于7的下标
	cout<<pos1<<" "<<a[pos1]<<endl;
	cout<<pos2<<" "<<a[pos2]<<endl;
	sort(a,a+6,greater<int>());  //按从大到小排序
	print(a,6); 
	int pos3=lower_bound(a,a+6,7,greater<int>())-a; //返回数组中第一个小于或等于7的下标 
	int pos4=upper_bound(a,a+6,7,greater<int>())-a; //返回数组中第一个小于7的下标 
	cout<<pos3<<" "<<a[pos3]<<endl;
	cout<<pos4<<" "<<a[pos4]<<endl;
	return 0;	
}
posted @ 2021-03-02 23:06  Dazzling!  阅读(49)  评论(0编辑  收藏  举报