當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ std::upper_bound()用法及代碼示例

std::upper_bound()

std::upper_bound() 是一個 STL 庫函數,屬於算法頭庫,在一個範圍內找到搜索元素的上界。上限表示搜索元素的排序範圍中的下一個較大元素。

假設範圍是:[4, 5, 6, 9, 12] 並且搜索元素是6,那麽上限是9本身。如果搜索元素為 7,則上限將再次為 9。

案例:

  1. 當存在搜索元素時:
    std::upper_bound()返回一個迭代器到搜索元素的下一個更大的元素
  2. 當搜索元素不存在時:
    1. 如果所有元素都大於搜索元素:
      upper_bound()返回一個迭代器到範圍的開始。
    2. 如果所有元素都低於搜索元素:
      upper_bound()返回到範圍末尾的迭代器(不存在上限)。
    3. 否則,
      upper_bound()返回到範圍內搜索元素(比搜索元素大的最近元素)的下一個更大元素的迭代器。

要使用 upper_bound(),需要對範圍進行排序。

用法:

ForwardIterator upper_bound(
    ForwardIterator first, 
    ForwardIterator last, 
    const T& searching_element
    );

參數:

  • ForwardIterator first:iterator 到範圍的開始
  • ForwardIterator last:iterator 到範圍的末尾
  • const T& searching_elementT是數據類型和searching_element是要找到上限的元素

返回類型:返回類型是在範圍內找到的上限的迭代器。

C++ 實現:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> arr{ 6, 5, 9, 12, 4 };
 
    //sort before using upper_bound()
    sort(arr.begin(), arr.end());

    int searching_element = 6;
    vector<int>::iterator it;
    it = upper_bound(arr.begin(), arr.end(), searching_element);
    
    //if all elements are smaller than the searching 
    //element then no upper bound exists
    if (it == arr.end()) {
        cout << "No upper bound exists\n";
    }
    else
        cout << "Upperr bound of " << searching_element << ":" << *it << endl;

    searching_element = 7;

    it = upper_bound(arr.begin(), arr.end(), searching_element);
    
    //if all eleemnts are smaller than the searching 
    //element then no upper bound exists
    if (it == arr.end()) {
        cout << "No upper bound exists\n";
    }
    else
        cout << "Upper bound of " << searching_element << ":" << *it << endl;

    return 0;
}

輸出:

Upperr bound of 6:9
Upper bound of 7:9

在上麵的 upper_bound() 函數中,使用默認比較器運算符 '<' 來比較元素之間。

但是我們有一個擴展版本函數,它使用用戶定義的比較器來比較黑白元素。

ForwardIterator upper_bound(
    ForwardIterator first, 
    ForwardIterator last, 
    const T& searching_element, 
    Comparator comp
    );

參數:

  • ForwardIterator first:iterator 到範圍的開始
  • ForwardIterator last:iterator 到範圍的末尾
  • const T& searching_elementT是數據類型和searching_element是要找到上限的元素
  • Comparator comp:用戶定義的比較器

返回類型:返回類型是在範圍內找到的上限的迭代器。

如果您有用戶定義的數據類型,這會很有幫助。



相關用法


注:本文由純淨天空篩選整理自 std::upper_bound() function with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。