函式模板
<algorithm>

std::upper_bound

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

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

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

lower_bound 不同,此函式返回的迭代器指向的值不能等於 val,只能大於。

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

引數

first, last
向前迭代器指向已排序(或正確分割槽)序列的起始和結束位置。使用的範圍是 [first,last),它包含 first 和 last 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
val
要在範圍內搜尋的上界值。
對於 (1)T 應為支援與範圍 [first,last) 中的元素作為 operator< 的左側運算元進行比較的型別。
comp
二元函式,接受兩個引數(第一個始終為 val,第二個為 ForwardIterator 指向的型別),並返回一個可轉換為 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) 中的物件。

異常

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

另見