lower_bound和upper_bound学习笔记

lower_bound和upper_bound均利用了二分查找算法,在一个数组中进行查数。

lower_bound(begin,end,x)-数组名。从begin位置到end-1位置,查找第一个大于等于x的数的位置。如果不存在,返回的是end

upper_bound(begin,end,x)-数组名。从begin位置到end-1位置,查找第一个大于x的数的位置。如果不存在,返回的是end

#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
int main()
{
    int a[10]={0,3,4,2};        // 0 2 3 4 
    sort(a,a+4);
    int l=upper_bound(a,a+4,32)-a;        // 不存在 输出4 
    int l=upper_bound(a,a+4,2)-a;        // 输出1 
    int l=upper_bound(a,a+4,4)-a;        //输出 3 
}

如果要返回最后一个小于等于x的位置,直接在上面获取的下标-1即可。

lower_bound( begin,end,num,greater<type>() )-num,从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,不存在则返回end-1。

upper_bound( begin,end,num,greater<type>() )-num,从数组的begin位置到end-1位置二分查找第一个小于num的数字,不存在则返回end-1。

以上参考于:https://blog.csdn.net/qq_40160605/article/details/80150252

关于这个东西的应用,有我的这篇题解的D题:https://www.cnblogs.com/liyexin/p/12716741.html

原文地址:https://www.cnblogs.com/liyexin/p/12729341.html