zoukankan      html  css  js  c++  java
  • lower_bound( )与upper_bound( )学习

    转自:https://blog.csdn.net/qq_40160605/article/details/80150252,这个讲的非常全面!

    1.从小到大排序的数组

    lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标

    upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

    #include <iostream>
    #include<vector>
    #include<algorithm>
    int main(){
        int num[6]={1,2,4,7,15,34};
        sort(num,num+6);                           //按从小到大排序
        int pos1=lower_bound(num,num+6,7)-num;    //返回数组中第一个大于或等于被查数的值
        int pos2=upper_bound(num,num+6,7)-num;
        cout<<pos1<<" "<<pos2<<endl;
        vector<int> num2={0,1,2,3,6};//也可以在vector中
        sort(num2.begin(),num2.end());
        int p1=lower_bound(num2.begin(),num2.end(),6)-num2.begin();
        int p2=upper_bound(num2.begin(),num2.end(),6)-num2.begin();
        cout<<p1<<" "<<p2<<endl;
        return 0;
    }
    
    //3 4
    4 5

    2.从大到小排序的数组

    重载lower_bound()和upper_bound():

    lower_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

    upper_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

    int cmd(int a,int b){
        return a>b;
    }
    int main(){
        int num[6]={1,2,4,7,15,34};
        sort(num,num+6,cmd);                           //按从大到小排序
        int p1=lower_bound(num,num+6,7,greater<int>())-num;//小于等于
        int p2=upper_bound(num,num+6,7,greater<int>())-num;//小于
        cout<<p1<<" "<<p2;
        return 0;
    }
    
    //2 3
  • 相关阅读:
    Less与Sass
    JQuery基础
    JS中DOM以及BOM
    JS函数入门
    JS入门
    响应式布局和弹性布局,移动开发常用技巧
    CSS基础1
    H5入门
    error C2143: syntax error : missing ';' before 'type'
    Windows系统下nodejs安装及配置
  • 原文地址:https://www.cnblogs.com/BlueBlueSea/p/13826493.html
Copyright © 2011-2022 走看看