C++ STL 之 lower_bound and upper_bound

头文件:#include< algorithm >

1.lower_bound (first, last, const_val)
返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

2.upper_bound(first, last, const_val)
返回大于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

举例如下:
一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标

pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。
pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。
pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。

//uva10474
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=10000;
int main()
{
    int arr[maxn],n,q,x,i,p,count=0;
    while(scanf("%d %d",&n,&q)==2&& n)
    {
        printf("CASE# %d:\n",++count);
        for(i=0;i<n;i++)
            scanf("%d",&arr[i]);
        sort(arr,arr+n);
        while(q--)
        {
            scanf("%d",&x);
            p=lower_bound(arr,arr+n,x)-arr;
            if(arr[p]==x) printf("%d found at %d\n",x,p+1);
                else printf("%d not found\n",x);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值