码迷,mamicode.com
首页 > 其他好文 > 详细

STL 源码剖析 算法 stl_algo.h -- binary_search

时间:2014-07-19 23:29:59      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   for   

本文为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
*/


STL 源码剖析 算法 stl_algo.h -- binary_search,布布扣,bubuko.com

STL 源码剖析 算法 stl_algo.h -- binary_search

标签:style   blog   http   color   io   for   

原文地址:http://blog.csdn.net/zhengsenlie/article/details/37967619

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!