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

来源:互联网 发布:神经网络算法入门书籍 编辑:程序博客网 时间:2024/04/28 18:26

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



binary_search

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

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

源码:

//version 1template <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 2template <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: presentSearching for 2: presentSearching for 3: presentSearching for 4: not presentSearching for 5: presentSearching for 6: not presentSearching for 7: not presentSearching for 8: presentSearching for 9: not presentSearching for 10: not present*/


0 0
原创粉丝点击