1.对于一个从小到大排序的数组,lower_bound(begin,end,x),upper_bound(begin,end,x) 前者查找成功返回的是从地址begin到end-1中第一个大于或者等于x的地址,后者查找成功返回的是从地址begin到end-1中第一个大于x的地址,减去begin恰好为数组下标。查找失败返回end。
2.对于一个从大到小排序的数组,lower_bound(begin,end,x,greater < int >()),upper_bound(begin,end,x,greater< int >())
前者查找成功返回的是从地址begin到end-1中第一个小于或者等于x的地址,后者查找成功返回的是从地址begin到end-1中第一个小于x的地址,减去begin恰好为数组下标。查找失败返回end。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int a[5]={0,1,1,2,3};
vector<int> v={0,1,1,2,3};
int main()
{
int ans=0;
ans=lower_bound(a,a+5,1)-a;
cout<<ans<<endl;//1
ans=upper_bound(a,a+5,1)-a;
cout<<ans<<endl;//3
ans=lower_bound(a,a+5,4)-a;
cout<<ans<<endl;//5
ans=upper_bound(a,a+5,4)-a;
cout<<ans<<endl;//5
ans=lower_bound(v.begin() ,v.end() ,1)-v.begin();
cout<<ans<<endl;//1
ans=upper_bound(v.begin() ,v.end() ,1)-v.begin();
cout<<ans<<endl;//3
ans=lower_bound(v.begin() ,v.end() ,4)-v.begin() ;
cout<<ans<<endl;//5
ans=upper_bound(v.begin() ,v.end() ,4)-v.begin() ;
cout<<ans<<endl;//5
//a[5]={3,2,1,1,0}
sort(a,a+5,greater<int>());
ans=lower_bound(a,a+5,1,greater<int>())-a;
cout<<ans<<endl;//2
ans=upper_bound(a,a+5,1,greater<int>())-a;
cout<<ans<<endl;//4
ans=lower_bound(a,a+5,4,greater<int>())-a;
cout<<ans<<endl;//0
return 0;
}