在STL标准函数库中提供了一些查找函数,如:lower_bound( )、upper_bound( )和binary_search( )。它们的底层实现方式都是二分查找,需要注意的是,使用它们时都需要满足前提条件:即在一个已经排好序的数组中进行查找,且默认是非递减的数组,因为它们是查找第一个大于或等于查找数值的位置,所以需要容器处于有序的状态。
若数组未排序,我们可以用sort( )函数对数组进行排序(sort( )函数的具体用法可以参考:Algorithm头文件--sort()函数_PL_涵的博客-优快云博客),若该数组是递减排序,我们可以使用reverse( )函数将数组逆序,或者传入自定义的查找方式。
使用函数查找的时间复杂度为O(log n)。
一、lower_bound()以及upper_bound()函数简介
1. 函数简介
两个函数的原型为:iterator lower_bound/upper_bound(start, end, num, find)
其中四个参数分别表示:
1)start表示查找开始的地址。
2)end表示查找结束的地址。
3)num表示查找的数值。
4)find为可选参数,表示查找方式,默认是对非降序数组进行查找。
函数返回值是一个迭代器,即一个指针。
2.函数用法
lower_bound( ):从容器的 start 位置到 end 位置的左闭右开区间内,使用二分查找第一个大于或等于 num 的数值。若找到,则返回该数值的地址;若不存在,则返回 end 。
一般的,我们可以通过返回的地址减去起始地址 start ,就可以得到数值在数组中的下标,或者是容器中小于 num 的数值的个数。
upper_bound( ):从容器的 start 位置到 end 位置的左闭右开区间内,二分查找第一个大于 num 的数值。若找到,则返回该数值的地址;若不存在,则返回 end 。
同样的,通过返回的地址减去起始地址 start ,就可以得到数值在数组中的下标,或者是容器中小于等于 num 的数值的个数。
前面,我们说到这两个函数默认是对非降序的数组进行查找,那么,如果数组是降序的,而我们又不想改变数组的顺序时该怎么办呢?这个时候,就需要用到第四个参数 find 了。
find参数与sort( ) 函数中的cmp参数一样的,实际上就是对lower_bound()和upper_bound()重载。
具体重载形式如下:
lower_bound( start, end, num, greater<type>( ) ):从容器的 start 位置到 end 位置的左闭右开区间内,二分查找第一个小于或等于 num 的数值,找到则返回该数值的地址;不存在则返回 end 。
upper_bound( start, end, num, greater<type>( ) ):从容器的 start 位置到 end 位置的左闭右开区间内,二分查找第一个小于 num 的数值,找到则返回该数值的地址;不存在则返回 end 。
#include<bits/stdc++.h>
using namespace std;
bool cmp(int a, int b){
return a > b;
}
int main(){
int num[] = {1, 2, 4, 7, 15, 34};
sort(num, num + 6); //按从小到大排序
int pos1 = lower_bound(num, num + 6, 7) - num;
//返回数组中第一个大于或等于被查数的值
int pos2 = upper_bound(num, num + 6, 7) - num;
//返回数组中第一个大于被查数的值
cout << pos1 << " " << num[pos1] << endl;
cout << pos2 << " " << num[pos2] << endl;
sort(num, num + 6, cmd); //按从大到小排序
int pos3 = lower_bound(num, num + 6, 7, greater<int>()) - num;
//返回数组中第一个小于或等于被查数的值
int pos4 = upper_bound(num, num + 6, 7, greater<int>()) - num;
//返回数组中第一个小于被查数的值
cout << pos3 << " " << num[pos3] << endl;
cout << pos4 << " " << num[pos4] << endl;
return 0;
}
实战例题:实战例题(第十一届蓝桥杯省赛真题-整数小拼接)_PL_涵的博客-优快云博客
二、binary_search()函数简介
1. 函数简介
函数原型为:bool binary_search( start, end, num )
其中三个参数分别表示:
1)start表示查找开始的地址。
2)end表示查找结束的地址。
3)num表示查找的数值。
其返回值为bool类型。
2. 函数用法
binary_search( ):从容器的 start 位置到 end 位置的左闭右开区间内,二分查找 num ,找到则返回 true,不存在则返回 false。
#include<bits/stdc++.h>
using namespace std;
int main() {
int a[] = {45, 31, 20, 12, 7};
if(binary_search(a, a + 5, 7))
cout << "查找成功!" << endl;
//输出“查找成功!”
return 0;
}