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;//返回该元素在数组中的下标。
    }
    
  • 相关阅读:
    结对第二次作业——某次疫情统计可视化的实现
    结对第一次—疫情统计可视化(原型设计)
    寒假作业(2/2)——疫情统计
    软工实践寒假作业(1/2)
    3DMAX三维编辑命令FFD的使用
    个人作业——软件工程实践总结&个人技术博客
    个人作业——软件评测
    结对第二次作业——某次疫情统计可视化的实现
    软工实践寒假作业(2/2)
    软工实践寒假作业(1/2)
  • 原文地址:https://www.cnblogs.com/forward-985/p/13775640.html
Copyright © 2011-2022 走看看