名稱空間
變體
操作

std::lower_bound

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

ForwardIt lower_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 lower_bound( ForwardIt first, ForwardIt last,

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

ForwardIt lower_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 lower_bound( ForwardIt first, ForwardIt last,

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

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

1) 順序由 operator< 決定

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

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

(C++20 前)

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

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

目錄

[編輯] 引數

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

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

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

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

型別要求
-
ForwardIt 必須滿足 LegacyForwardIterator 的要求。
-
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 不是 舊式隨機訪問迭代器,則迭代器增量的數量與 N 成線性關係。值得注意的是,std::mapstd::multimapstd::setstd::multiset 迭代器不是隨機訪問的,因此應優先使用它們的成員 lower_bound 函式。

[編輯] 可能的實現

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

lower_bound (1)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type>
ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value)
{
    return std::lower_bound(first, last, value, std::less{});
}
lower_bound (2)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type,
         class Compare>
ForwardIt lower_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(*it, value))
        {
            first = ++it;
            count -= step + 1;
        }
        else
            count = step;
    }
 
    return first;
}

[編輯] 注意

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

std::binary_search 不同,std::lower_bound 不要求 operator<comp 是非對稱的(即 a < bb < a 總是產生不同的結果)。實際上,它甚至不要求 value < *itercomp(value, *iter) 對於 [firstlast) 中的任何迭代器 iter 都是良好形式的。

特性測試 標準 特性
__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 < 8; ++i)
    {
        // Search for first element x such that i ≤ x
        auto lower = std::lower_bound(data.begin(), data.end(), i);
 
        std::cout << i << " ≤ ";
        lower != data.end()
            ? std::cout << *lower << " at index " << std::distance(data.begin(), lower)
            : std::cout << "not found";
        std::cout << '\n';
    }
 
    std::vector<PriceInfo> prices{{100.0}, {101.5}, {102.5}, {102.5}, {107.3}};
 
    for (const double to_find : {102.5, 110.2})
    {
        auto prc_info = std::lower_bound(prices.begin(), prices.end(), to_find,
            [](const PriceInfo& info, double value)
            {
                return info.price < value;
            });
 
        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}};
    auto cmpz = [](CD x, CD y) { return x.real() < y.real(); };
    #ifdef __cpp_lib_algorithm_default_value_type
        auto it = std::lower_bound(nums.cbegin(), nums.cend(), {2, 0}, cmpz);
    #else
        auto it = std::lower_bound(nums.cbegin(), nums.cend(), CD{2, 0}, cmpz);
    #endif
    assert((*it == CD{2, 2}));
}

輸出

0 ≤ 1 at index 0
1 ≤ 1 at index 0
2 ≤ 2 at index 1
3 ≤ 4 at index 2
4 ≤ 4 at index 2
5 ≤ 5 at index 3
6 ≤ 6 at index 5
7 ≤ not found
102.5 at index 2
110.2 not found

[編輯] 缺陷報告

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

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

[編輯] 另請參閱

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