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

☆樱花仙子☆ 提交于 2020-02-17 06:25:41

概述

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.

复杂度

应用举例

缺省原型调用

// 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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!