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
廣告