C++ 算法库 - lower_bound() 函数



描述

C++ 函数std::algorithm::lower_bound() 查找第一个不小于给定值的元素。此函数要求元素按排序顺序排列。它使用运算符<进行比较。

声明

以下是来自 std::algorithm 头文件的 std::algorithm::lower_bound() 函数声明。

C++98

template <class ForwardIterator, class T>
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last,
   const T& val);

参数

  • first − 指向初始位置的正向迭代器。

  • last − 指向最终位置的正向迭代器。

  • val − 要在范围内搜索的下界的数值。

返回值

返回指向第一个不小于给定值的元素的迭代器。如果范围内的所有元素都小于val,则函数返回last.

异常

如果元素比较或迭代器上的操作引发异常,则抛出异常。

请注意,无效参数会导致未定义的行为。

时间复杂度

线性。

示例

以下示例演示了 std::algorithm::lower_bound() 函数的用法。

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

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 5, 13, 14};
   auto it = lower_bound(v.begin(), v.end(), 2);

   cout << "First element which greater than 2 is " << *it << endl;

   it = lower_bound(v.begin(), v.end(), 30);

   if (it == end(v))
      cout << "All elements are less than 30" << endl;
   return 0;
}

让我们编译并运行上面的程序,这将产生以下结果:

First element which greater than 2 is 2
All elements are less than 30
algorithm.htm
广告
© . All rights reserved.