STL 二分查找

实现源码:https://www.cnblogs.com/cobbliu/archive/2012/05/21/2512249.html


 

1.在一个递增的数组(或vector)中查找元素属于[ s , e ) 的下标

 

int main()
{
    const int n=10;
              //0 1 2 3 4 5 6 7 8 9
    int arr[n]={1,2,3,4,5,5,5,5,9,10};
    int s,e;
    I("%d%d",&s,&e);
    int s_pos=lower_bound(arr,arr+n,s)-arr;
    int e_pos=upper_bound(arr,arr+n,e)-arr;
    O("%d,%d\n",s_pos,e_pos);
    return 0;
}

 


2.查找递增数组中元素是否存在

使用binary_search

 

注:

对于结构体,要么重载小于符号:

①bool operator<(const struct b) const

②要么定义有小于符号含义的cmp函数。

 


 3.应用在递减序列中

#include<cstdio> 
#include<stdlib.h> 
#include<algorithm>

using namespace std;

bool cmp(int x,int y){
    return x>y;
}

int main(){
    int asc[10]={0,1,2,3,4,5,6,7,8,9};
    int desc[10]={9,8,7,6,5,4,3,2,1,0};
    int obj=8;
    int p1=upper_bound(asc,asc+10,obj)-asc;
    int p2=upper_bound(desc,desc+10,obj,cmp)-desc;
    printf("%d,%d\n",p1,p2) ;
    return 0;
}
View Code

 

posted @ 2018-02-07 20:16  TQCAI  阅读(275)  评论(0编辑  收藏  举报