lower_bound和upper_bound的一些总结

54 篇文章 0 订阅

 头文件:<algorithm>

lower_bound和upper_bound都是用在有序的数组或者容器中的!(以下函数并非是函数原型 只是为了便于说明 可能并不严谨 想看函数原型的请戳这个网址:https://baike.baidu.com/item/lower_bound/8620039?fr=aladdin)

lower_bound(begin,end,value) 可以在区间[begin,end) (注意是左闭右开区间)内二分查找第一个大于等于value的元素,并返回该元素的位置。(指针 或者说迭代器)如果没有的话则返回end。

upper_bound(begin,end,value) 在区间[begin,end)内二分查找第一个大于value的元素,并返回该元素的位置;没有的话返回end。

这个版本的两个函数排序依据的是底层的 <(小于)操作符,下面还有一个版本依据comp进行排序。(即函数的第四个参数 支持我们自己写的函数)也就是说,上面的两个我们常用于升序数组的二分(从小到大);下面我们介绍用于降序数组的二分(从大到小)。

lower_bound(begin,end,value,greater<type>()) 可以在区间[begin,end) (注意是左闭右开区间)内二分查找第一个小于等于value的元素,并返回该元素的位置。(指针 或者说迭代器)如果没有的话则返回end。

upper_bound(begin,end,value,greater<type>()) 在区间[begin,end)内二分查找第一个小于value的元素,并返回该元素的位置;没有的话返回end。

传入的那个函数也是C++库中实现好的,知道可以这样用就行了。(会用STL优先队列的对这两个函数应该不陌生吧?)

上面说过了,这个函数返回的是指针(迭代器),因此对于数组而言,如果要得到对应的下标的话应该这么写:

int a[10];
int index=lower_bound(a,a+10,5)-a;

如果要直接修改值的话,可以这么写:

(这样写是有隐患的 当你确保一定有解的时候可以这么写 不然的话老老实实加上判断)

int a[10];
*lower_bound(a,a+10,5)=7;

多说无益,我们看几个例子,就懂了。

数组升序:

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;

int a[5];

int main()
{
    int n=5;//5个元素
    a[0]=1,a[1]=3,a[2]=5,a[3]=7,a[4]=9;//升序
    cout<<lower_bound(a,a+n,5)-a<<endl;//得到的是下标 2
    cout<<upper_bound(a,a+n,5)-a<<endl;//得到的是下标 3
    *lower_bound(a,a+n,5)=6;
    for(int i=0;i<n;i++)
        cout<<a[i]<<' ';    // 1 3 6 7 9
    cout<<endl;
    *upper_bound(a,a+n,7)=10;
    for(int i=0;i<n;i++)
        cout<<a[i]<<' ';    // 1 3 6 7 10
    cout<<endl;
    return 0;
}

数组降序:

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;

int a[5];

int main()
{
    int n=5;//5个元素
    a[0]=9,a[1]=7,a[2]=5,a[3]=3,a[4]=1;//降序
    cout<<lower_bound(a,a+n,5,greater<int>())-a<<endl;//得到的是下标 2
    cout<<upper_bound(a,a+n,5,greater<int>())-a<<endl;//得到的是下标 3
    *lower_bound(a,a+n,5,greater<int>())=6;
    for(int i=0;i<n;i++)
        cout<<a[i]<<' ';    // 9 7 6 3 1
    cout<<endl;
    *upper_bound(a,a+n,5,greater<int>())=4;
    for(int i=0;i<n;i++)
        cout<<a[i]<<' ';    // 9 7 6 4 1
    cout<<endl;
    return 0;
}

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值