• std:: lower_bound std:: upper_bound


    std:: lower_bound

    该函数返回范围内第一个不小于(大于或等于)指定val的值。如果序列中的值都小于val,则返回last.序列应该已经有序!

    eg:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    int main(int argv,char **argc)
    {
      vector<int> v1{1,2,3,4};
      cout<<"v1=";
      for(int i:v1)
        cout<<i<<" ";
      cout<<endl;
      auto it=lower_bound(v1.begin(),v1.end(),3);
      cout<<"lower_bound(v1.begin(),v1.end(),3)="<<*it<<endl;
      auto it2=lower_bound(v1.begin(),v1.end(),5);
      if(it2==v1.end())
        cout<<"lower_bound(v1.begin(),v1.end(),5)=v1.end()"<<endl;
      else
        cout<<"lower_bound(v1.begin(),v1.end(),5)="<<*it2<<endl;
    
    }

    截图:

    std:: upper_bound

    该函数返回范围内第一个 大于 指定val的值。如果序列中的值都小于val,则返回last.序列应该已经有序!

    eg:

    #include <iostream>     // std::cout
    #include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
    #include <vector>       // std::vector
    
    int main () {
      int myints[] = {10,20,30,30,20,10,10,20};
      std::vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20
    
      std::sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30
    
      std::vector<int>::iterator low,up;
      low=std::lower_bound (v.begin(), v.end(), 20); //          ^
      up= std::upper_bound (v.begin(), v.end(), 20); //                   ^
    
      std::cout << "lower_bound at position " << (low- v.begin()) << '
    ';
      std::cout << "upper_bound at position " << (up - v.begin()) << '
    ';
    
      return 0;
    }

    截图:

    另外,在map里的使用方法:

    // map::lower_bound/upper_bound
    #include <iostream>
    #include <map>
    
    int main ()
    {
      std::map<char,int> mymap;
      std::map<char,int>::iterator itlow,itup;
    
      mymap['a']=20;
      mymap['b']=40;
      mymap['c']=60;
      mymap['d']=80;
      mymap['e']=100;
    
      itlow=mymap.lower_bound ('b');  // itlow points to b
      itup=mymap.upper_bound ('d');   // itup points to e (not d!)
    
      mymap.erase(itlow,itup);        // erases [itlow,itup)
    
      // print content:
      for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
        std::cout << it->first << " => " << it->second << '
    ';
    
      return 0;
    }

    结果:

    a => 20
    e => 100
  • 相关阅读:
    ibatis的优缺点及可行性分析
    NHibernate优点和缺点:
    IbatisNet的介绍和使用
    bat(续七)-for语句(循环结构)
    bat(续五)-获取批处理文件所在路径
    Shell函数参数
    Shell函数:Shell函数返回值、删除函数、在终端调用函数
    Shell break和continue命令
    Shell until循环
    Shell while循环
  • 原文地址:https://www.cnblogs.com/jiu0821/p/5306997.html
Copyright © 2020-2023  润新知