Namespaces
Variants

std:: lower_bound

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
lower_bound
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
定义于头文件 <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 起)

在已分区的范围 [ first , last ) 中,查找首个 value 之前排序的元素。

1) 排序顺序由 operator < 决定:

返回 [ first , last ) 中第一个满足 bool ( * iter < value ) false 的迭代器 iter ,若不存在则返回 last

[ first , last ) 中的元素 elem 未按表达式 bool ( elem < value ) 进行 分区 ,则行为未定义。

(C++20 前)

等价于 std :: lower_bound ( first, last, value, std:: less { } )

(C++20 起)
2) 顺序由 comp 决定:
返回范围 [ first , last ) 中第一个满足 bool ( comp ( * iter, value ) ) false 的迭代器 iter ,若不存在这样的迭代器则返回 last
如果范围 [ first , last ) 中的元素 elem 未按表达式 bool ( comp ( elem, value ) ) 进行 分区 ,则行为未定义。

目录

参数

first, last - 定义待检查元素的分区 范围 的迭代器对
value - 用于与元素比较的值
comp - 二元谓词,若第一个参数排序在第二个之前则返回​ true

谓词函数的签名应等价于如下形式:

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

虽然签名不必包含 const & ,但函数不得修改传递给它的对象,且必须能够接受所有(可能为 const 的) Type1 Type2 类型的值,无论其 值类别 为何(因此不允许 Type1 & ,也不允许 Type1 ,除非对于 Type1 移动操作等价于拷贝操作 (C++11 起) )。
类型 Type1 必须满足:类型为 ForwardIt 的对象在解引用后能隐式转换到 Type1 。类型 Type2 必须满足:类型为 T 的对象能隐式转换到 Type2 。 ​

类型要求
-
ForwardIt 必须满足 LegacyForwardIterator 的要求。
-
Compare 必须满足 BinaryPredicate 的要求。不要求满足 Compare 的要求。

返回值

指向范围 [ first , last ) 中首个不小于 value 的元素的迭代器,若找不到此类元素则返回 last

复杂度

给定 N std:: distance ( first, last )

1) 最多进行 log 2 (N)+O(1) 次与 value 的比较,使用 operator < (C++20 前) std:: less { } (C++20 起)
2) 最多需要 log 2 (N)+O(1) 次比较器 comp 的应用。

然而,若 ForwardIt 不满足 LegacyRandomAccessIterator 要求,迭代器递增次数将与 N 呈线性关系。特别需要注意的是, std::map std::multimap std::set std::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 仅要求 [ first , last ) 区间满足分区条件,但该算法通常用于 [ first , last ) 已排序的情况,这样对于任意 value 都能确保二分搜索的有效性。

std::binary_search 不同, std::lower_bound 不要求 operator < comp 具有反对称性(即不要求 a < b b < a 始终产生不同结果)。实际上,它甚至不要求对于区间 [ first , last ) 中的任何迭代器 iter ,表达式 value < * iter comp ( value, * 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)
    {
        // 搜索第一个满足 i ≤ x 的元素
        auto lower = std::lower_bound(data.begin(), data.end(), i);
        std::cout << i << " ≤ ";
        lower != data.end()
            ? std::cout << *lower << " 位于索引 " << std::distance(data.begin(), lower)
            : std::cout << "未找到";
        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 << " 位于索引 " << prc_info - prices.begin()
            : std::cout << to_find << " 未找到";
        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 位于索引 0
1 ≤ 1 位于索引 0
2 ≤ 2 位于索引 1
3 ≤ 4 位于索引 2
4 ≤ 4 位于索引 2
5 ≤ 5 位于索引 3
6 ≤ 6 位于索引 5
7 ≤ 未找到
102.5 位于索引 2
110.2 未找到

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 应用于 发布时行为 正确行为
LWG 270 C++98 Compare 需要满足 Compare T 需要
LessThanComparable (要求严格弱序)
仅需满足划分要求;
允许异构比较
LWG 384 C++98 最多允许 log(N)+1 次比较 修正为 log 2 (N)+1
LWG 2150 C++98 若在 [ first , last ) 中存在迭代器 iter 使得
bool ( comp ( * iter, value ) ) false ,则 std::lower_bound
可能返回 [ iter , last ) 中的任意迭代器
不能返回 iter 之后的
任何迭代器

参见

返回匹配特定键的元素范围
(函数模板)
将元素范围划分为两组
(函数模板)
定位已划分范围的分割点
(函数模板)
返回指向第一个 大于 某值的元素的迭代器
(函数模板)
返回指向第一个 不小于 给定键的元素的迭代器
( std::set<Key,Compare,Allocator> 的公开成员函数)
返回指向第一个 不小于 给定键的元素的迭代器
( std::multiset<Key,Compare,Allocator> 的公开成员函数)
返回指向第一个 不小于 给定值的元素的迭代器
(算法函数对象)