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 } 

  • 相关阅读:
    数据持久化编程学习总结
    Boost Replaceable by C++11 language features or libraries
    【敬业福bug】支付宝五福卡敬业福太难求 被炒至200元
    由文字生成path后制作写字的动画
    CSS经典布局之弹性布局
    HDU2082 找单词 【母函数】
    HDOJ 题目2475 Box(link cut tree去点找祖先)
    DELPHI中MDI子窗口的关闭 和打开
    sql语句中日期相减的操作
    Delphi编码规范
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/6961035.html
Copyright © 2011-2022 走看看