版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42623428/article/details/84037087
首先,使用的前提是排好序的非递减数组。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,得到找到数字在数组中的下标。
如果是在从大到小的排序数组中:
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 <bits/stdc++.h>
using namespace std;
int main()
{
int a[1001];
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n);
int l=lower_bound(a,a+n,m)-a; //返回数组中第一个大于或等于查找数的值
int r=upper_bound(a,a+n,m)-a; //返回数组中第一个大于查找数的值
cout<<l<<" "<<a[l];
cout<<r<<" "<<a[r];
sort(a,a+n,greater<int>());
int x=lower_bound(a,a+n,m,greater<int>())-a;
int y=upper_bound(a,a+n,m,greater<int>())-a;
cout<<x<<" "<<a[x];
cout<<y<<" "<<a[y];
}