名稱空間
變體
操作

std::upper_bound

來自 cppreference.com
< cpp‎ | 演算法
 
 
演算法庫
有約束演算法與針對範圍的演算法 (C++20)
有約束的演算法,例如 ranges::copyranges::sort 等……
執行策略 (C++17)
排序及相關操作
劃分操作
排序操作
二分搜尋操作
(於已劃分範圍上)
upper_bound
集合操作(於已排序範圍上)
歸併操作(於已排序範圍上)
堆操作
最小/最大值操作
(C++11)
(C++17)
字典序比較操作
排列操作
C 庫
數值操作
未初始化記憶體上的操作
 
定義於標頭檔案 <algorithm>
(1)
template< class ForwardIt, class T >

ForwardIt upper_bound( ForwardIt first, ForwardIt last,

                       const T& value );
(C++20 起為 constexpr)
(直到 C++26)
template< class ForwardIt, class T = typename std::iterator_traits

                                         <ForwardIt>::value_type >
constexpr ForwardIt upper_bound( ForwardIt first, ForwardIt last,

                                 const T& value );
(C++26 起)
(2)
template< class ForwardIt, class T, class Compare >

ForwardIt upper_bound( ForwardIt first, ForwardIt last,

                       const T& value, Compare comp );
(C++20 起為 constexpr)
(直到 C++26)
template< class ForwardIt, class T = typename std::iterator_traits

                                         <ForwardIt>::value_type,
          class Compare >
constexpr ForwardIt upper_bound( ForwardIt first, ForwardIt last,

                                 const T& value, Compare comp );
(C++26 起)

在分割槽範圍 [firstlast) 中搜索第一個在 value 之後排序的元素。

1) 排序由 operator< 決定

返回 [firstlast) 中第一個迭代器 iter,其中 bool(value < *iter)true,如果不存在這樣的 iter 則返回 last

如果 [firstlast) 中的元素 elem 未根據表示式 bool(value < elem) 進行分割槽,則行為未定義。

(C++20 前)

等價於 std::upper_bound(first, last, value, std::less{})

(C++20 起)
2) 排序由 comp 決定
返回 [firstlast) 中第一個迭代器 iter,其中 bool(comp(value, *iter))true,如果不存在這樣的 iter 則返回 last
如果 [firstlast) 中的元素 elem 未根據表示式 bool(comp(value, elem)) 進行分割槽,則行為未定義。

目錄

[編輯] 引數

first, last - 定義要檢查的元素已分割槽範圍的迭代器對。
value - 用於比較元素的數值
comp - 二元謂詞,如果第一個引數排在第二個引數之前,則返回true

謂詞函式的簽名應等效於以下內容:

 bool pred(const Type1 &a, const Type2 &b);

雖然簽名不需要包含 const &,但函式不得修改傳遞給它的物件,並且必須能夠接受 Type1Type2 型別(可能是 const)的所有值,而無論其值類別如何(因此,不允許使用 Type1 &,除非對於 Type1,移動等同於複製,否則也不允許使用 Type1(C++11 起))。
型別 Type1 必須使得型別為 T 的物件可以隱式轉換為 Type1。型別 Type2 必須使得型別為 ForwardIt 的物件可以被解引用然後隱式轉換為 Type2

型別要求
-
ForwardIt 必須滿足 LegacyForwardIterator 的要求。
-
Compare 必須滿足二元謂詞 (BinaryPredicate)的要求。它不需要滿足比較 (Compare)的要求。

[編輯] 返回值

指向範圍 [firstlast) 中第一個在 value 之後排序的元素的迭代器,如果未找到此類元素,則為 last

[編輯] 複雜度

給定 N 作為 std::distance(first, last)

1) 最多進行 log2(N)+O(1) 次與 value 的比較,使用operator<(C++20 前)std::less{}(C++20 起)
2) 最多進行 log2(N)+O(1) 次比較器 comp 的應用。

然而,如果 ForwardIt 不是舊式隨機訪問迭代器 (LegacyRandomAccessIterator),則迭代器增量的次數與 N 成線性關係。值得注意的是,std::mapstd::multimapstd::setstd::multiset 迭代器不是隨機訪問迭代器,因此應優先使用它們的成員 upper_bound 函式。

[編輯] 可能的實現

另請參見 libstdc++libc++ 中的實現。

upper_bound (1)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type>
ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value)
{
    return std::upper_bound(first, last, value, std::less{});
}
upper_bound (2)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type,
         class Compare>
ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value, Compare comp)
{
    ForwardIt it;
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    count = std::distance(first, last);
 
    while (count > 0)
    {
        it = first; 
        step = count / 2;
        std::advance(it, step);
 
        if (!comp(value, *it))
        {
            first = ++it;
            count -= step + 1;
        } 
        else
            count = step;
    }
 
    return first;
}

[編輯] 注意

儘管 std::upper_bound 只要求 [firstlast) 是分割槽好的,但此演算法通常用於 [firstlast) 已排序的情況,以便二分查詢對於任何 value 都有效。

對於 [firstlast) 中的任何迭代器 iterstd::upper_bound 要求 value < *itercomp(value, *iter) 是格式良好的,而 std::lower_bound 則要求 *iter < valuecomp(*iter, value) 是格式良好的。

特性測試 標準 特性
__cpp_lib_algorithm_default_value_type 202403 (C++26) 演算法的列表初始化 (1,2)

[編輯] 示例

#include <algorithm>
#include <cassert>
#include <complex>
#include <iostream>
#include <vector>
 
struct PriceInfo { double price; };
 
int main()
{
    const std::vector<int> data{1, 2, 4, 5, 5, 6};
 
    for (int i = 0; i < 7; ++i)
    {
        // Search first element that is greater than i
        auto upper = std::upper_bound(data.begin(), data.end(), i);
 
        std::cout << i << " < ";
        upper != data.end()
            ? std::cout << *upper << " at index " << std::distance(data.begin(), upper)
            : std::cout << "not found";
        std::cout << '\n';
    }
 
    std::vector<PriceInfo> prices{{100.0}, {101.5}, {102.5}, {102.5}, {107.3}};
 
    for (double to_find : {102.5, 110.2})
    {
        auto prc_info = std::upper_bound(prices.begin(), prices.end(), to_find,
            [](double value, const PriceInfo& info)
            {
                return value < info.price;
            });
 
        prc_info != prices.end()
            ? std::cout << prc_info->price << " at index " << prc_info - prices.begin()
            : std::cout << to_find << " not found";
        std::cout << '\n';
    }
 
    using CD = std::complex<double>;
    std::vector<CD> nums{{1, 0}, {2, 2}, {2, 1}, {3, 0}, {3, 1}};
    auto cmpz = [](CD x, CD y) { return x.real() < y.real(); };
    #ifdef __cpp_lib_algorithm_default_value_type
        auto it = std::upper_bound(nums.cbegin(), nums.cend(), {2, 0}, cmpz);
    #else
        auto it = std::upper_bound(nums.cbegin(), nums.cend(), CD{2, 0}, cmpz);
    #endif
    assert((*it == CD{3, 0}));
}

輸出

0 < 1 at index 0
1 < 2 at index 1
2 < 4 at index 2
3 < 4 at index 2
4 < 5 at index 3
5 < 6 at index 5
6 < not found 
107.3 at index 4
110.2 not found

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 270 C++98 Compare 需要滿足 比較,且 T 需要
可小於比較的(需要嚴格弱序)
只需要分割槽;
允許異構比較
LWG 384 C++98 最多允許 log2(N)+1 次比較 更正為 log2(N)+O(1)
LWG 577 C++98 last 不能被返回 允許
LWG 2150 C++98 如果 [firstlast) 中存在任何迭代器 iter,使得
bool(comp(value, *iter))truestd::upper_bound
可以返回 [iterlast) 中的任何迭代器
iter 之後不能返回迭代器
不能返回在 iter 之後的迭代器

[編輯] 另請參見

返回與特定鍵匹配的元素範圍
(函式模板) [編輯]
返回一個指向第一個不小於給定值的元素的迭代器
(函式模板) [編輯]
將一個範圍的元素分成兩組
(函式模板) [編輯]
定位一個已劃分範圍的劃分點
(函式模板) [編輯]
返回一個指向第一個大於某個值的元素的迭代器
(演算法函式物件)[編輯]
返回指向第一個大於給定鍵的元素的迭代器
(std::set<Key,Compare,Allocator> 的公開成員函式) [編輯]
返回指向第一個大於給定鍵的元素的迭代器
(std::multiset<Key,Compare,Allocator> 的公開成員函式) [編輯]