迭代lower_bound和upper_bound的总结

  • 二分搜索方面,STL在库中提供了binary_search,lower_bound,upper_bound.

  • lower_bound是一种应用于有序数据范围内的算法,他可以返回一个迭代器,这个迭代器指向第一个不小于指定值value的元素。

  • 通过它,我们可以找出第一个能够恰当插入value的位置,又能维持指定范围内的元素顺序(有序状态)。

  • 相对的upper_bound返回的迭代器指向第一个大于指定值value的元素

  • 拿酒来一波

#include <iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;

int main()
{
    int a[14]= {1,1,2,2,2,4,5,5,6,8,8,8,10,15};
    int *pos;
    int idx;
    pos=lower_bound(a,a+14,3);
    idx=distance(a,pos);
    printf("a[%d] = %d\n",idx,*pos);///a[5]=4

    pos=lower_bound(a,a+14,2);
    idx=distance(a,pos);
    printf("a[%d] = %d\n",idx,*pos);///a[2]=2
    return 0;
}

  • 分析一下上面代码:
  • lower_bound()的前面两个参数用来指定作为对象的数组或容器的范围,比如lower_bound(a,a+14,3),
  • 他指定数组a的头指针以及距离头指针14的位置,既数组的末尾。
  • 如果a是vector,则可以使用a,begin()和a.end()来指定范围。
  • lower_bound()的第三个参数用于指定value。上面的value为3,而数组中第一个不小于3的元素为a[5]=4
  • 所以程序将指向a[5]的指针赋值给了*pos
  • distance函数用于返回两个指针间的距离,
  • 比如:distance(a,pos)会返回a的开头到pos的距离=5
  • 那就再上一波
  • 滴答滴答---题目链接
  • #include <iostream>
    #include<string.h>
    #include<stdio.h>
    #include<algorithm>
    using namespace std;
    const int maxn=1e5+10;
    int main()
    {
        int n;
        int a[maxn];
        scanf("%d",&n);
        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
        int sum=0;
        int m;
        scanf("%d",&m);
        for(int i=0; i<m; i++)
        {
            int x;
            scanf("%d",&x);
            if(*(lower_bound(a,a+n,x))==x)
            {
                sum++;
            }
        }
        printf("%d\n",sum);
        return 0;
    }
    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值