C++ STL binary_search 函数说明

2020-06-06  本文已影响0人  book_02

1. 说明

用二分查找的方法检查指定值val是否在范围[first,last)内存在

找到了,返回 true ; 没找到,返回 false 。

注意:

  1. 范围[first,last)内的元素要求是有序的。

函数签名如下:

template< class ForwardIt, class T >
bool binary_search( ForwardIt first, ForwardIt last, const T& value );

2. 头文件

#include <algorithm>

3. 例子


#include <iostream>
#include <vector>
#include <algorithm>


int main(int argc, char **argv) 
{  
    std::vector<int> nums = { 1, 3, 4, 5, 9 };

    std::sort(nums.begin(), nums.end());          

    std::cout << std::binary_search(nums.begin(), nums.end(), 2) << endl;
    std::cout << std::binary_search(nums.begin(), nums.end(), 3) << endl;
  
    return 0;
}

结果:

0
1

4. 参考

https://en.cppreference.com/w/cpp/algorithm/binary_search

上一篇 下一篇

猜你喜欢

热点阅读