upper_bound与lower_bound

upper_bound和lower_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()和upper_bound()

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>
#include<vector>
using namespace std;

bool cmp(int a,int b)
{
    return a>b;
}

int main()
{
    int a[6]={3,2,5,1,3,10};
    //1 2 3 3 5 10
    sort(a,a+6);
    cout<<*lower_bound(a+1,a+6+1,3)<<endl;
    cout<< lower_bound(a+1,a+6+1,3)-a<<endl;//返回该元素在数组中的下标。
    
    vector<int>b={3,2,5,1,3,10};
    //1 2 3 3 5 10
    sort(b.begin(),b.end());
    cout<<*--upper_bound(b.begin(),b.end(),1)<<endl;
    cout<<--upper_bound(b.begin(),b.end(),1)-b.begin()<<endl;
    //返回第一个<=1的数
    //10 5 3 3 2 1
    sort(a,a+6,cmp);
    cout<<*lower_bound(a+1,a+6+1,3,greater<int>())<<endl;
    cout<< lower_bound(a+1,a+6+1,3,greater<int>())-a<<endl;//返回该元素在数组中的下标。
}
posted @ 2020-10-06 21:43  30天CF上蓝!!!  阅读(100)  评论(0编辑  收藏  举报