首页 > 其他 > 详细

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

时间:2015-04-19 19:31:14      阅读:278      评论:0      收藏:0      [点我收藏+]

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;
}
技术分享

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

原文:http://blog.csdn.net/u013167299/article/details/45131287

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!