STL之排序与检索--lower_bound()函数与upper_bound()函数

在STL的库中提供了一个函数叫作:lower_bound(容器或数组名, 检索长度, key);
分别介绍一下这三个参数,容器或数组名指的是排序内容的其实地址,例如要对某数组a[10],容器或数组名就应该是a,又例如有一个不定长数组vector v,那么第一个参数容器或者数组名就应该是v.begin();第二个参数指明排序内容的长度,对于数组,那么就是数组的长度(根据情况而定,比如数组长度是10, 但是需要排序的元素只有前5个,这时候就要灵活一点),那么对于不定长数组第二个参数就是v.end()啦;第三个参数很简单,就是我们需要检索的目标,也叫作key;
在这里说一个很重要的点,使用这个函数进行检索的容器或者数组,需要里面的元素有序!!!!!
这个函数的返回值,是排序内容中第一个大于等于key的元素的下标!!!!
在这里使用两个小demo讲一下这个函数的用法:
1.使用lower_bound函数对不定长数组vector进行元素的检索:

#include <iostream>
#include <cstdio>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>

using namespace std;

int main()
{
    //我们先定义一个vector
    vector<int> v;
    for (int i = 0; i < 5; ++i)
    {
        int temp;
        scanf("%d", &temp);
        v.push_back(temp);
    }
    printf("%d\n", lower_bound(v.begin(), v.end(), 3) - v.begin());
    return 0;
}

2. 使用lower_bound函数对数组进行检索

#include <iostream>
#include <cstdio>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>

using namespace std;

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 7, 8, 8};
    printf("%d", lower_bound(arr, arr + 8, 6) - arr);
    return 0;
}

在这种情况下的输出为5;

与lower_bound相对应的是upper_bound,这个函数的用法就不再描述了。

最后,再用一个UVa上的题目,帮助大家理解一下这个函数的用法和好处,该题目的来自UVa 10474;
题目意思:现在又N个大理石,每个大理石上写了一个非负整数。首先把各个数从小到大进行排序,然后回答Q个问题。每个问题询问是否有一个大理石写着某个整数x,如果是,还要回答哪个大理石上写着x。排序后的大理石从左到右编号为1~N。
输入样例:
4 1
2 3 5 1
5
5 2
1 3 3 3 1
2 3
输出样例:
CASE# 1:
5 found at 4
CASE# 2:
2 not found
3 found at 3

#include <iostream>
#include <cstdio>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>

using namespace std;

int main()
{
    int n;
    int q;
    int x;
    int a[1000];
    int kase = 1;
    int flag = false;
    while (scanf("%d %d", &n, &q) == 2 && n)
    {
        for (int i = 0; i < n; ++i)
        {
            scanf("%d", &a[i]);
        }
        sort(a, a + n);
        while (q--)
        {
            scanf("%d", &x);
            int p = lower_bound(a, a + n, x) - a;
            if (!flag)
            {
                printf("CASE# %d:\n", kase);
                flag = true;
            }
            if (a[p] == x)
            {
                printf("%d found at %d\n", x, p + 1);
            }
            else
            {
                printf("%d not found \n");
            }
        }
        flag = false;
        ++kase;
    }
    return 0;
}
***end***
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值