扫盲:lower_bound&upper_bound

· · 个人记录

基本用法

lower_bound

lower_bound(a,a+n,k)返回一个指针(可视为int类型),指向长度为 n 且下标从 0 开始的的序列 a 中第一个大于等于 k 的元素,其中序列 a 为单调不降序列。如果这样的元素不存在,则指针指向a+n,即序列的末尾(最后一个元素的后一位)。lower_bound函数被包含在algorithm头文件中。

以下为用法示例:

输入

第一行一个数 n,表示单调不降序列 a 的长度。

接下来一行 n 个数,第 i 个数为 a_i。

最后一行一个数 k,表示待查找的数。

12
1 3 4 5 7 8 8 8 10 12 16 19
8

输出

一行一个整数 p,表示第一个大于等于 k 的数在序列 a 中的位置。

5

代码

#include<iostream>
#include<algorithm>
using namespace std;

int n,k,a[1005];

int main(){
    cin>>n;
    for(int i=0;i<n;i++) cin>>a[i];
    cin>>k;
    cout<<lower_bound(a,a+n,k)-a;
    return 0;
}

upper_bound

upper_bound(a,a+n,k)返回一个指针(可视为int类型),指向长度为 n 且下标从 0 开始的的序列 a 中第一个大于 k 的元素,其中序列 a 为单调不降序列。如果这样的元素不存在,则指针指向a+n,即序列的末尾(最后一个元素的后一位)。upper_bound函数被包含在algorithm头文件中。

以下为用法示例:

输入

第一行一个数 n,表示单调不降序列 a 的长度。

接下来一行 n 个数,第 i 个数为 a_i。

最后一行一个数 k,表示待查找的数。

12
1 3 4 5 7 8 8 8 10 12 16 19
8

输出

一行一个整数 p,表示第一个大于 k 的数在序列 a 中的位置。

8

代码

#include<iostream>
#include<algorithm>
using namespace std;

int n,k,a[1005];

int main(){
    cin>>n;
    for(int i=0;i<n;i++) cin>>a[i];
    cin>>k;
    cout<<upper_bound(a,a+n,k)-a;
    return 0;
}

拓展用法

百度百科上列举了两种lower_bound与upper_bound的版本,我这里以lower_bound为例,放出简化后的代码:

  1. lower_bound(a,a+n,k)

这种版本即是上文中所说的基础用法。

  1. lower_bound(a,a+n,k,cmp)

这种版本相比上一个版本,多了一个参数 cmp。cmp 是一个布尔类型的函数,它充当函数的比较器。在第一种版本中,比较器默认为 <,也可认为是less<>()。

这种版本的lower_bound和upper_bound一般利用在单调不升序列的查找中。此时,cmp 也就是比较器应为 >,也可认为是greater<>()。

如果你要在单调不升序列里利用lower_bound或upper_bound查找元素,要注意两点:

  1. 比较器应为 >,前文已说过。

  2. 此时lower_bound返回的指针指向第一个小于等于待查找元素的元素,而upper_bound返回的指针指向第一个小于待查找元素的元素。如果这样的元素不存在,则指针指向a+n,即序列的末尾(最后一个元素的后一位)。可以发现,用了比较器 > 后,lower_bound和upper_bound的性质与原本的性质正好相反。

关于greater和less:

greater<类型>()和less<类型>()是头文件functional里的“函数”。准确来讲,它们是伪函数,因为它们重载了运算符“()”,使它们“看起来像函数”。

这里另外提一句:如果比较器是 < 而待查找序列为单调不升序列,或者比较器是 > 而待查找序列为单调不降序列,则lower_bound和upper_bound会发生一些奇妙的错误。

请看下面的程序与对应的两组输入输出,感受lower_bound和upper_bound的作用。

程序

#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;

int n,k,a[1005];

int main(){
    cin>>n;
    for(int i=0;i<n;i++) cin>>a[i];
    cin>>k;
    cout<<lower_bound(a,a+n,k)-a<<endl<<upper_bound(a,a+n,k)-a<<endl;
    cout<<lower_bound(a,a+n,k,greater<int>())-a<<endl<<upper_bound(a,a+n,k,greater<int>())-a<<endl;
    cout<<lower_bound(a,a+n,k,less<int>())-a<<endl<<upper_bound(a,a+n,k,less<int>())-a;
    return 0;
}

输入#1

9
1 2 2 3 7 13 13 13 18
13

输出#1

5
8
0
0
5
8

输入#2

9
18 13 13 13 7 3 2 2 1
13

输出#2

9
9
1
4
9
9