C++ std::lower_bound()和std::upper_bound()函数使用

函数定义

std::lower_bound 返回第一个大于等于value值的迭代器,如果没有查找到,则返回无效迭代器;std::lower_bound returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value, or last if no such element is found.

std::upper_bound返回第一个大于value值的迭代器,如果没有查找到,返回无效迭代器;std::upper_bound returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.

这个两个函数内部使用的都是二分查找法,被查找的对象必须是有序的,否则会出现非期望结果。

测试代码

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    std::vector<int> data = { 1, 3, 4, 5, 5, 6 };
    size_t input_data = 1;
    for(; input_data < data.size(); input_data++)
    {
        std::cout << "input data is : " << input_data << std::endl;
        auto iter_lower = std::lower_bound(data.begin(), data.end(), input_data);
        if (iter_lower != data.end())
        {
            std::cout << "lower data[index] is:" << *iter_lower
                      << " >= " << input_data  << " lower index : "
                      << std::distance(data.begin(), iter_lower) << std::endl;
        }
        auto iter_upper = std::upper_bound(data.begin(), data.end(), input_data);
        if (iter_upper != data.end())
        {
            std::cout << "upper data[index] is:" << *iter_upper
                      << " > " << input_data << " upper index : "
                      << std::distance(data.begin(), iter_upper) << std::endl;
        }
    }
    return 0;
}

测试输出

input data is : 1
lower data[index] is:1 >= 1 lower index : 0
upper data[index] is:3 > 1 upper index : 1
input data is : 2
lower data[index] is:3 >= 2 lower index : 1
upper data[index] is:3 > 2 upper index : 1
input data is : 3
lower data[index] is:3 >= 3 lower index : 1
upper data[index] is:4 > 3 upper index : 2
input data is : 4
lower data[index] is:4 >= 4 lower index : 2
upper data[index] is:5 > 4 upper index : 3
input data is : 5
lower data[index] is:5 >= 5 lower index : 3
upper data[index] is:6 > 5 upper index : 5

算法效率

  • 由于该算法采用的是二分法进行查找,因此对于可随机访问的有序容器使用 algorithm 库中的 lower_bound 和 upper_bound 函数时间复杂度为O(logn),但对于set,multiset这种不能随机访问的有序容器,要用其自带的 lower_bound 和 upper_bound 的时间复杂度才为 O(logn)。

参考资料

C++中的std::lower_bound()和std::upper_bound()函数-CSDN博客.

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值