C++ 演算法庫 - lower_bound() 函式



描述

C++ 函式std::algorithm::lower_bound() 查詢第一個不小於給定值的元素。此函式期望元素按排序順序排列。它使用二元函式進行比較。

宣告

以下是來自 std::algorithm 標頭檔案的 std::algorithm::lower_bound() 函式的宣告。

C++98

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

引數

  • first - 指向初始位置的前向迭代器。

  • last - 指向最終位置的前向迭代器。

  • val - 要在範圍內搜尋的下界的值。

  • comp - 一個二元函式,它接受兩個引數並返回 bool 值。

返回值

返回一個指向第一個不小於給定值的元素的迭代器。如果範圍內所有元素都小於val,則函式返回last.

異常

如果任一二元函式或迭代器上的操作丟擲異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

線性。

示例

以下示例顯示了 std::algorithm::lower_bound() 函式的使用方法。

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

using namespace std;

bool ignore_case(char a, char b) {
   return(tolower(a) == tolower(b));
}

int main(void) {
   vector<char> v = {'A', 'b', 'C', 'd', 'E'};
   auto it = lower_bound(v.begin(), v.end(), 'C');

   cout << "First element which is greater than \'C\' is " << *it << endl;

   it = lower_bound(v.begin(), v.end(), 'C', ignore_case);

   cout << "First element which is greater than \'C\' is " << *it << endl;

   it = lower_bound(v.begin(), v.end(), 'z', ignore_case);

   cout << "All elements are less than \'z\'." << endl;

   return 0;
}

讓我們編譯並執行上述程式,這將產生以下結果:

First element which is greater than 'C' is b
First element which is greater than 'C' is d
All elements are less than 'z'.
algorithm.htm
廣告