函式模板
<algorithm>

std::lower_bound

預設 (1)
template <class ForwardIterator, class T>  ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,                               const T& val);
自定義 (2)
template <class ForwardIterator, class T, class Compare>  ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,                               const T& val, Compare comp);
返回下界的迭代器
返回一個迭代器,指向範圍 [first,last) 中第一個不小於 val 的元素。

對於第一個版本,元素使用 operator< 進行比較,第二個版本使用 comp 進行比較。範圍中的元素應已根據相同的標準(operator<comp排序,或者至少相對於 val 分割槽

該函式透過比較已排序範圍中的非連續元素來最佳化比較次數,這對於隨機訪問迭代器特別高效。

upper_bound 不同,此函式返回的迭代器指向的元素也可能等於 val,而不僅僅是大於。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template <class ForwardIterator, class T>
  ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
  ForwardIterator it;
  iterator_traits<ForwardIterator>::difference_type count, step;
  count = distance(first,last);
  while (count>0)
  {
    it = first; step=count/2; advance (it,step);
    if (*it<val) {                 // or: if (comp(*it,val)), for version (2)
      first=++it;
      count-=step+1;
    }
    else count=step;
  }
  return first;
}

引數

first, last
Forward iterators 指向已排序(或正確分割槽)序列的起始和結束位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
val
要在範圍內搜尋的下界值。
對於 (1)T 應為支援與範圍 [first,last) 中的元素進行比較的型別,其中元素作為 operator< 的右側運算元。
comp
二元函式,接受兩個引數(第一個是 ForwardIterator 指向的型別,第二個始終是 val),並返回一個可轉換為 bool 的值。返回的值指示第一個引數是否被認為排在第二個引數之前。
該函式不得修改其任何引數。
這可以是指向函式的指標,也可以是函式物件。

返回值

指向 val 在範圍內的下界的迭代器。
如果範圍內的所有元素都小於 val,則函式返回 last

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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,up;
  low=std::lower_bound (v.begin(), v.end(), 20); //          ^
  up= std::upper_bound (v.begin(), v.end(), 20); //                   ^

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

  return 0;
}

輸出
lower_bound at position 3
upper_bound at position 6


複雜度

平均而言,對 firstlast 之間的距離進行對數運算:執行大約 log2(N)+1 次元素比較(其中 N 是此距離)。
對於隨機訪問迭代器,迭代器前進本身會在平均情況下產生額外的線性複雜度。

資料競爭

訪問範圍 [first,last) 中的物件。

異常

如果元素比較或迭代器操作引發異常,則丟擲。
請注意,無效引數會導致未定義行為

另見