概述
C++ STL提供了标准二分查找相关实现。如下图所示,来自http://www.cplusplus.com/reference/algorithm/。
对应的函数功能如下表
函数名 | 函数作用 |
binary_search | 在指定的范围内,使用二分查找某个值 |
lower_bound | 在指定的范围内,使用二分查找某个值的左下界 |
upper_bound | 在指定的范围内,使用二分查找某个值的右上界 |
equal_range | 在指定的范围内,使用二分查找某个值位置范围,即左下界到右上界 |
upper_bound函数
函数作用
Return iterator to upper bound
Returns an iterator pointing to the first element in the range [first,last)
which compares greater than val.
使用前提
1、包含对应的 STL 头文件。即
#include <algorithm>
2、需要包括命名空间 std。即
using namespace std;
或者使用显式调用命名空间。即
std::lower_bound(...);
3、查找的数列必须有序。
函数原型
来自http://www.cplusplus.com/reference/algorithm/upper_bound/。函数原型定义如下图所示。
The elements are compared using operator<
for the first version, and comp for the second. 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.
Unlike lower_bound, the value pointed by the iterator returned by this function cannot be equivalent to val, only greater.
输入参数
first, last
第一参数为起始地址,第二个为结束地址。注意:它是左闭右开的(即不包括结束地址对应的那个值)。
val
第三个参数为要找的值。
comp
用户自定义的比较函数。可以不提供。
返回值
An iterator to the upper bound position for val in the range.
If no element in the range compares greater than val, the function returns last.
复杂度
。
应用举例
缺省原型调用
// upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
std::vector<int>::iterator up;
up= std::upper_bound (v.begin(), v.end(), 20); // ^
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
系统输出
upper_bound at position 6