使用这两个函数都需要包含对应头文件
#include <algorithm>
这两个函数都是采用的二分算法
lower_bound(查找的起始位置,查找的终止为止,需要查找的数 )是返回第一个大于等于需要查找的数的数的地址
比如,要a[]数组中,从[1,n]中第一个大于s的数的下标
pos=lower_bound(a+1,a+n+1,s)-a;
upper_bound(查找的起始位置,查找的终止为止,需要查找的数 )是返回第一个大于需要查找的数的数的地址
注意上面的两种用法都需要原数组是小到大排列的有序数组
可以通过修改比较器,查找第一个小于或小于等于某个数的地址
数组需要从大到小排列
首先需要比较函数
bool cmp(const int &a,const int &b){return a>b;}
比如,要a[]数组中,从[1,n]中第一个小于s的数的下标
pos=lower_bound(a+1,a+n+1,s,cmp)-a;
也可以不写cmp函数,将所有cmp的位置换成greater<i/nt>() 去掉/,int显示不了
这两种函数如果差找不到目标,就返回查找的最后一个元素的地址
代码示例
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(const int &a,const int &b)
{
return a>b;
}
int main()
{
int a[]={1,5,9,11,45,69,101};
cout<<"数组为 ";
for(int i=0;i<7;i++)cout<<a[i]<<" ";cout<<endl;
int p1=lower_bound(a,a+7,9)-a;
cout<<"数组中第一个大于等于9的数的下标为 "<<p1<<endl;
int p2=upper_bound(a,a+7,9)-a;
cout<<"数组中第一个大于9的数的下标为 "<<p2<<endl;
sort(a,a+7,cmp);
cout<<"数组为 ";
for(int i=0;i<7;i++)cout<<a[i]<<" ";cout<<endl;
int p3=lower_bound(a,a+7,9,cmp)-a;
cout<<"数组中第一个小于等于9的数的下标为 "<<p3<<endl;
int p4=upper_bound(a,a+7,9,greater<int>())-a;
cout<<"数组中第一个小于9的数的下标为 "<<p4<<endl;
}
结果