zoukankan      html  css  js  c++  java
  • 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;//返回该元素在数组中的下标。
    }
    
  • 相关阅读:
    怎么获取数组中的对象的某一项之和
    原型链
    js的事件循环(Eventloop) 机制/js的宏任务微任务执行顺序
    怎么替换数组中对象的属性
    求对象所有值的和
    sequelize中duplicating:false的使用
    WebSocket
    轮播

    ssl tsl
  • 原文地址:https://www.cnblogs.com/forward-985/p/13775640.html
Copyright © 2011-2022 走看看