• 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;//返回该元素在数组中的下标。
    }
    
  • 相关阅读:
    Mysql基础3-数据操作语言DML-数据查询语言DQL
    Mysql基础2-数据定义语言DDL
    Mysql基础1-基础语法-字段类型
    php源码建博客5--建库建表-配置文件-错误日志
    PHP基础4--函数-数组
    php源码建博客4--实现MVC结构微型框架
    PHP基础3--文件加载-错误处理
    php源码建博客3--区分平台的MVC结构
    php源码建博客2--实现单入口MVC结构
    php源码建博客1--搭建站点-实现登录页面
  • 原文地址:https://www.cnblogs.com/forward-985/p/13775640.html
Copyright © 2020-2023  润新知