C++ STL lower_bound、upper_bound
头文件:#include< algorithm >
lower_bound(数组开始查找的地址,数组查找结束的后一个地址,要查找的数)
lower_bound、upper_bound的二分实现模板
int lowerr_bound(int a[],int l,int r,int k){
while(l<=r){
int mid=l+r>>1;
if(a[mid]<k) l=mid+1;
else r=mid-1;
}
return l;
}
int upperr_bound(int a[],int l,int r,int k){
while(l<=r){
int mid=l+r>>1;
if(a[mid]<=k) l=mid+1;
else r=mid-1;
}
return l;
}
lower_bound、upper_bound的应用例子如下
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int lowerr_bound(int a[],int l,int r,int k){
while(l<=r){
int mid=(l+r)>>1;
if(a[mid]<k) l=mid+1;
else r=mid-1;
}
return l;
}
int upperr_bound(int a[],int l,int r,int k){
while(l<=r){
int mid=l+r>>1;
if(a[mid]<=k) l=mid+1;
else r=mid-1;
}
return l;
}
int main(){
int a[]={1,2,3,4,5,6,7,8,9};
int n=sizeof a /sizeof (int);
cout<<n<<endl;
printf("lower_bound():%d\n",lower_bound(a,a+n,6)-a);
printf("upper_bound():%d\n",upper_bound(a,a+n,6)-a);
printf("lowerr_bound()%d\n",lowerr_bound(a,0,n-1,6));
printf("upperr_bound()%d\n",upperr_bound(a,0,n-1,6));
return 0;
}
输出结果如下:
版权声明:本文为weixin_46028214原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。