zoukankan      html  css  js  c++  java
  • STL 源代码分析 算法 stl_algo.h -- binary_search

    本文为senlie原创。转载请保留此地址:http://blog.csdn.net/zhengsenlie



    binary_search

    ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    描写叙述:利用 lower_bound 实现二分查找,返回 bool

    源代码:

    //version 1
    template <class ForwardIterator, class T>
    bool binary_search(ForwardIterator first, ForwardIterator last,
                       const T& value) {
      ForwardIterator i = lower_bound(first, last, value);
      return i != last && !(value < *i);
    }
    //version 2
    template <class ForwardIterator, class T, class Compare>
    bool binary_search(ForwardIterator first, ForwardIterator last, const T& value,
                       Compare comp) {
      ForwardIterator i = lower_bound(first, last, value, comp);
      return i != last && !comp(value, *i);
    }

    演示样例:
    int main()
    {
      int A[] = { 1, 2, 3, 3, 3, 5, 8 };
      const int N = sizeof(A) / sizeof(int);
    
    
      for (int i = 1; i <= 10; ++i) {
        cout << "Searching for " << i << ": "
             << (binary_search(A, A + N, i) ? "present" : "not present") << endl;
      }
    }
    /*
    The output is:
    Searching for 1: present
    Searching for 2: present
    Searching for 3: present
    Searching for 4: not present
    Searching for 5: present
    Searching for 6: not present
    Searching for 7: not present
    Searching for 8: present
    Searching for 9: not present
    Searching for 10: not present
    */
    


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    python中自定义模块导入
    EditText------Android
    Fragment类实现
    Android文件访问
    python中pip使用国内镜像提高安装速度
    esri/geometry包 (arcgis api for js)
    【CSDN 编辑器 MarkDowm 使用技巧】
    for 循环 :从指定下标开始,并指定步长
    【车牌识别】-车牌中字符分割代码详解
    【 Linux 常用命令】
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4833015.html
Copyright © 2011-2022 走看看