1. 说明
用二分查找的方法检查指定值val是否在范围[first,last)内存在
找到了,返回 true ; 没找到,返回 false 。
注意:
- 范围[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
网友评论