lower_bound( )和upper_bound( )
lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。
/*
lower_bound(begin,end,num) 从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,
不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标
upper_bound(begin,end,num) 从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,
不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标
在从大到小的排序数组中
lower_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,
不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,
不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
*/
补充
可以利用cmp函数来实现如lower_bound对降序数组使用
#include <iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
using namespace std;
bool cmp(const int &a,const int &b){
return a>b;
}
int main(){
int a[]={6,5,4,3,2,1};
cout<<lower_bound(a,a+6,3,cmp)-a;//减去数组地址才能得到正确的下标
return 0;
}

浙公网安备 33010602011771号