基于STL的二分查找——lower_bound函数

概述

C++ STL提供了标准二分查找相关实现。如下图所示,来自http://www.cplusplus.com/reference/algorithm/

对应的函数功能如下表

函数名函数作用
binary_search在指定的范围内,使用二分查找某个值
lower_bound在指定的范围内,使用二分查找某个值的左下界
upper_bound在指定的范围内,使用二分查找某个值的右上界
equal_range在指定的范围内,使用二分查找某个值位置范围,即左下界到右上界

lower_bound函数

函数作用

Return iterator to lower bound

Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.

使用前提

1、包含对应的 STL 头文件。即

#include <algorithm>

2、需要包括命名空间 std。即

using namespace std;

或者使用显式调用命名空间。即

std::lower_bound(...);

3、查找的数列必须有序

函数原型

来自http://www.cplusplus.com/reference/algorithm/lower_bound/。函数原型定义如下图所示。

The elements are compared using operator< for the first version, and comp for the second. The elements in the range shall already be sorted according to this same criterion (operator< or comp), or at least partitioned with respect to val.

The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted range, which is specially efficient for random-access iterators.

Unlike upper_bound, the value pointed by the iterator returned by this function may also be equivalent to val, and not only greater.

输入参数

first, last

第一参数为起始地址,第二个为结束地址。注意:它是左闭右开的(即不包括结束地址对应的那个值)。

val

第三个参数为要找的值。

comp

用户自定义的比较函数。可以不提供。

返回值

An iterator to the lower bound of val in the range.

If all the element in the range compare less than val, the function returns last.

复杂度

O(log_{2}(N)+2)

应用举例

缺省原型调用

// lower_bound/upper_bound example
#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
#include <vector>       // std::vector

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  std::vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  std::sort(v.begin(), v.end());                // 10 10 10 20 20 20 30 30

  std::vector<int>::iterator low;
  low=std::lower_bound (v.begin(), v.end(), 20); //          ^

  std::cout << "lower_bound at position " << (low- v.begin()) << '\n';

  return 0;
}

系统输出

lower_bound at position 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

努力的老周

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

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

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

打赏作者

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

抵扣说明:

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

余额充值