概述
C++ STL提供了标准二分查找相关实现。如下图所示,来自http://www.cplusplus.com/reference/algorithm/。
对应的函数功能如下表
函数名 | 函数作用 |
binary_search | 在指定的范围内,使用二分查找某个值 |
lower_bound | 在指定的范围内,使用二分查找某个值的左下界 |
upper_bound | 在指定的范围内,使用二分查找某个值的右上界 |
equal_range | 在指定的范围内,使用二分查找某个值位置范围,即左下界到右上界 |
binary_search函数
函数作用
Test if value exists in sorted sequence
Returns true
if any element in the range [first,last)
is equivalent to val, and false
otherwise.
使用前提
1、包含对应的 STL 头文件。即
#include <algorithm>
2、需要包括命名空间 std。即
using namespace std;
或者使用显式调用命名空间。即
std::binary_search(...);
3、查找的数列必须有序。
函数原型
来自http://www.cplusplus.com/reference/algorithm/binary_search/。函数原型定义如下图所示。
The elements are compared using operator<
for the first version, and comp for the second. Two elements, a and b are considered equivalent if (!(a<b) && !(b<a))
or if (!comp(a,b) && !comp(b,a))
.
The elements in the range shall already be sorted according to this same criterion (operator<
or comp), or at least partitioned with respect to val.
The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted range, which is specially efficient for random-access iterators.
输入参数
first, last
第一参数为起始地址,第二个为结束地址。注意:它是左闭右开的(即不包括结束地址对应的那个值)。
val
第三个参数为要找的值。
comp
用户自定义的比较函数。可以不提供。
返回值
如果存在要找的元素,返回 true;否则返回 fasle。
复杂度
。
应用举例
缺省原型调用
// binary_search example
#include <iostream> // std::cout
#include <algorithm> // std::binary_search, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {1,2,3,4,5,4,3,2,1};
std::vector<int> v(myints,myints+9); // 1 2 3 4 5 4 3 2 1
// using default comparison:
std::sort (v.begin(), v.end());
std::cout << "looking for a 3... ";
if (std::binary_search (v.begin(), v.end(), 3)) {
std::cout << "found!\n";
} else {
std::cout << "not found.\n";
}
return 0;
}
系统输出
looking for a 3... found!
用户自定义原型调用
// binary_search example
#include <iostream> // std::cout
#include <algorithm> // std::binary_search, std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
int main () {
int myints[] = {1,2,3,4,5,4,3,2,1};
std::vector<int> v(myints,myints+9); // 1 2 3 4 5 4 3 2 1
// using myfunction as comp:
std::sort (v.begin(), v.end(), myfunction);
std::cout << "looking for a 6... ";
if (std::binary_search (v.begin(), v.end(), 6, myfunction)) {
std::cout << "found!\n";
} else {
std::cout << "not found.\n";
}
return 0;
}
系统输出
looking for a 6... not found.