zoukankan      html  css  js  c++  java
  • 二分检索函数lower_bound()和upper_bound()

    二分检索函数lower_bound()和upper_bound()

    一、说明

    头文件:<algorithm>

    二分检索函数lower_bound()和upper_bound()
    lower_bound():找到大于等于某值的第一次出现
    upper_bound():找到大于某值的第一次出现
    必须从小到大排序后才能用
    内部查找方式为二分查找,二分查找必定需要排序

    返回值为地址

    二、代码及结果

     1 /*
     2 二分检索函数lower_bound()和upper_bound() 
     3 lower_bound():找到大于等于某值的第一次出现
     4 upper_bound():找到大于某值的第一次出现
     5 必须从小到大排序后才能用 
     6 内部查找方式为二分查找,二分查找必定需要排序 
     7 返回值为地址 
     8 */
     9 #include <iostream>
    10 #include <algorithm>
    11 #include <string>
    12 using namespace std;
    13 
    14 
    15 int main(){
    16       
    17     int a[]={9,2,4,5,10,7,30};
    18     sort(a,a+7);//省略掉排序规则的形式,默认从小到大 
    19     //sort(a,a+7,less<int>());//用系统的排序规则,从小到大 
    20     //sort(a,a+7,greater<int>());//用系统的排序规则,从大到小 
    21     for(int i=0;i<7;i++){
    22         cout<<a[i]<<" "<<&a[i]<<endl;
    23     }
    24     cout<<endl; 
    25     /*
    26     这个lower_bound要从小到大排序才正确,
    27     如果是从大到小,或者不排序,还是输出的从小到大排序好后的位置 
    28     */
    29     int *p=lower_bound(a,a+7,2);//用lower_bound找大于等于2的第一次出现 
    30     cout<<p<<endl; 
    31     cout<<*p<<endl; 
    32     int *p1=upper_bound(a,a+7,2);//用upper_bound找大于等于2的第一次出现
    33     cout<<p1<<endl; 
    34     cout<<*p1<<endl;
    35     
    36     
    37     
    38     return 0;
    39 } 

  • 相关阅读:
    接口测试框架——第五篇-测试用例和运行用例
    接口测试框架——第四篇-url、excel内容等
    flex布局
    JSON 对象 与 字符串 互转
    nginx 拒绝本地ip访问
    supervisord
    工作中小玩意
    nginx 反向代理
    php获取当月天数及当月第一天及最后一天
    Homebrew 备忘
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/6961035.html
Copyright © 2011-2022 走看看