STL_lower_bound/upper_bound

1、lower_bound 和 upper_bound

1.1、lower_bound

lower_bound(起始地址first,结束地址last,要查找的数值val):

firstlast中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素地址。如果区间内所有元素都小于val,则返回last的地址,且last的地址是越界的。

1.2、upper_bound

upper_bound(起始地址first,结束地址last,要查找的数值val):

firstlast中的前闭后开区间进行二分查找,返回大于val的第一个元素地址。如果val大于区间内所有元素,则返回last的地址,且last的地址是越界的。

1.3、注意

特别注意:lower_bound/upper_bound二分查找的区间必须为有序。

在这里插入图片描述

因为lower_boundupper_bound返回的是数组元素的地址值,所以再减去数组首地址的值即该数组元素的下标。

2、降序序列

2.1、用法

降序序列使用lower_boundupper_bound

(1)lower_bound的正确写法为lower_bound(first, last, val, greater<int>()),或类似于sort排序,使用自定义比较函数。若val在序列中,则返回val第一次出现的位置,否则返回第一个插入val不影响原序列顺序的位置。

(2)upper_bound的正确写法为upper_bound(first, last, val, greater<int>()),或类似于sort排序,使用自定义比较函数。若val在序列中,则返回第一个小于val的位置,否则返回第一个插入val不影响原序列顺序的位置。

2.2、代码

//降序数组使用lower_bound/upper_bound的正确示例
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a[] = {4, 4, 3, 3, 2, 2, 1, 1};
    
    cout<< lower_bound(a, a+8, 0,greater<int>())-a <<endl; //输出
    cout<< lower_bound(a, a+8, 4,greater<int>())-a <<endl; //输出
    cout<< lower_bound(a, a+8, 1,greater<int>())-a <<endl; //输出
    cout<< lower_bound(a, a+8, 3,greater<int>())-a <<endl; //输出
    cout<< lower_bound(a, a+8, 5,greater<int>())-a <<endl; //输出

    cout<< upper_bound(a, a+8, 0,greater<int>())-a <<endl; //输出
    cout<< upper_bound(a, a+8, 4,greater<int>())-a <<endl; //输出
    cout<< upper_bound(a, a+8, 1,greater<int>())-a <<endl; //输出
    cout<< upper_bound(a, a+8, 3,greater<int>())-a <<endl; //输出
    cout<< upper_bound(a, a+8, 5,greater<int>())-a <<endl; //输出
    return 0;
}

3、binary_search 函数

STL里还有一个二分查找函数binary_search(first,last,val) ,用法类似于lower_bound/upper_bound,但它只能判断val是否在firstlast的有序区间里存在,如果val存在则返回true,否则返回false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zaiyang遇见

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值