因为有时候确实直接一行方便多了,当然有很多时候单纯这么写有些东西不好维护。
Update:
lower_bound返回第一个大于或等于被查数的值,那么如果找不到返回n+1,
如果结合题目不能取到n+1,可以在边界处变if(pos1==numb+1) pos1=numb;
不然的话到n+1对实际的max/min修正过程中无影响,下列形式判断
LL pos=lower_bound(a+1,a+1+n,x)-a; //找不到的话返回n+1
upper_bound返回数组中第一个大于被查数的值(其-1就是第一个小于等于的)
如果结合题目不能取pos=0,那就注意不能减到0。采取:pos=max(pos-1,1);
不然的话到0对实际的max/min修正过程中无影响,就下列形式
LL p1=upper_bound(a+1,a+1+n,b[i])-a-1; ///找到第一个大于的,然后-1 ///upper_bound(a+1,a+1+n,x)-a;找不到的话返回1 ///upper_bound(a+1,a+1+n,x)-a-1;找不到的话返回0
https://blog.youkuaiyun.com/qq_40160605/article/details/80150252(代码的例子来源)
#include<bits/stdc++.h>
using namespace std;
const int maxn=100000+10;
const int INF=2*int(1e9)+10;
#define LL long long
int cmd(int a,int b){
return a>b;
}
int main(){
int num[6]={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;
}