STL upper_bound(),lower_bound()函数的学习+自己的实现

STL里,这两个函数用于在有序的数组里找某个元素的位置,用法简单提一下upper_bound(begin,end,key),start是查找的起点,end是终点,key是关键值,lower_bound()用法一样,upper_bound()函数,返回第一个大于要找的值得位置(或者理解是这个元素的下一个位置),而Lower_bound是小于等于关键字的位置(或者理解为关键字第一次出现 的位置),

#include<bits/stdc++.h>
using namespace std;
const int maxn=2222;
int a[maxn];
int n;
int my_upper_bound(int num)
{
    int l=0;
    int h=n-1;
    while(l<=h)
    {
        int mid=(l+h)/2;
        if(num<a[mid])
            h=mid-1;
        else
            l=mid+1;
    }
    return l;
}
int my_lower_bound(int num)
{
    int l=0;
    int h=n-1;
    while(l<=h)
    {
        int mid=(l+h)/2;
        if(num>a[mid])
            l=mid+1;
        else
            h=mid-1;
    }
    return l;
}

int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>a[i];
    printf("my_upper_bound(4) 位置在 %d\n",my_upper_bound(4));
    printf("my_lower_bound(4) 位置在 %d\n",my_lower_bound(4));
    printf("lower_bound(4)    位置在 %d\n",lower_bound(a,a+n,4)-a);
    printf("upper_bound(4)    位置在 %d\n",upper_bound(a,a+n,4)-a);
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值