认识lower_bound()与upper_bound()

首先,提到这个函数,是需要他自己的头文件<algorithm>

举个例子:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
bool cmp(int a,int b)
{
    return a<b;
}
int main()
{
    int temp;
    int p[10]={2,4,6,5,5,5,9,3,3,3};
    sort(p,p+10,cmp);
    temp=lower_bound(p, p+10, 3)-p;
    printf("%d\n",temp);     //输出一
    temp=upper_bound(p, p+10, 3)-p;
    printf("%d\n",temp);      //输出二
    temp=*lower_bound(p, p+10, 6);
    printf("%d\n",temp);     //输出三
    temp=*upper_bound(p, p+10, 6);
    printf("%d\n",temp);     //输出四
    return 0;
}

sort后的p[10]={2,3,3,3,4,5,5,5,6,9};

认识一下这四个输出有什么不同:

输出一:1

输出二:4

输出三:6

输出四:9

那么让我们来认识一下“lower_bound-p”,“upper_bound-p”,“*lower_bound”与“*upper_bound”之间的区别
“lower_bound(p, p+n, c)-p”:得到第一个">=c"的数的位置
“upper_bound(p, p+n, c)-p”:得到第一个">c"的数的位置
“*lower_bound(p, p+n, c)”:得到第一个">=c"的数的
“*upper_bound(p, p+n, c)”:得到第一个">c"的数的


让我们用上述的结论举几个例子来证明一下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
bool cmp(int a,int b)
{
    return a<b;
}
int main()
{
    int temp;
    int p[10]={2,4,6,5,5,5,9,3,3,3};
    sort(p,p+10,cmp);
    temp=lower_bound(p, p+10, 4)-p;
    printf("%d\n",temp);
    temp=upper_bound(p, p+10, 4)-p;
    printf("%d\n",temp);
    temp=*lower_bound(p, p+10, 6);
    printf("%d\n",temp);
    temp=*upper_bound(p, p+10, 6);
    printf("%d\n",temp);
    return 0;
}

输出结果:

4

5

6

9



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuliwuliii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值