Namespaces
Variants

std::upper_bound

来自 zh.cppreference.net
 
 
算法库
受约束算法与范围算法 (C++20)
受约束算法,例如 ranges::copy、ranges::sort、...
排序和相关操作
划分操作
(C++11)    

排序操作
二分查找操作
(在已划分的范围上)
集合操作 (在已排序范围上)
合并操作 (在已排序范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作


 
定义于头文件 <algorithm>
template< class ForwardIt, class T >
ForwardIt upper_bound( ForwardIt first, ForwardIt last,
                       const T& value );
(1) (C++26 前)
(C++20 起 constexpr)
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 起)
template< class ForwardIt, class T, class Compare >
ForwardIt upper_bound( ForwardIt first, ForwardIt last,
                       const T& value, Compare comp );
(2) (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 起)

在已划分的范围 [first, last) 中查找符合特定顺序的首个元素,该元素排在 value 之后。

1) 顺序由 operator< 确定:

返回 iter 中满足 [first, last) 为 bool(value < *iter) 的首个迭代器 true,若不存在此类 last 则返回 iter。

如果 elem 的元素 [first, last) 未根据表达式 进行 划分bool(value < elem),则行为未定义。

(C++20 前)

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

(C++20 起)
2) 顺序由 comp 确定:
返回 iter 中满足 [first, last) 为 bool(comp(value, *iter)) 的首个迭代器 true,若不存在此类 last 则返回 iter。
如果 elem 的元素 [first, last) 未根据表达式 进行 划分bool(comp(value, elem)),则行为未定义。

参数

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

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

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

虽然签名不必包含 const & ,但函数不得修改传递给它的对象,且必须能够接受(可能为 const 的) Type1 与 Type2 类型的所有值,无论其 值类别 为何(因此不允许 Type1 & ,亦不允许 Type1 ,除非对于 Type1 而言移动等价于复制 (C++11 起) )。
类型 Type1 必须满足:类型 T 的对象能隐式转换为 Type1 。类型 Type2 必须满足:类型 ForwardIt 的对象在解引用后可隐式转换为 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 的迭代器不支持随机访问,因此应当优先使用它们各自的成员函数 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 仅要求 [ first , last ) 区间被划分,但该算法通常用于 [ first , last ) 已排序的情况,这样二分搜索对任意 value 都有效。

对于区间 [ first , last ) 中的任意迭代器 iter , std::upper_bound 要求表达式 value < * iter 和 comp ( value, * iter ) 必须合法,而 std::lower_bound 则要求 * iter < value 和 comp ( * 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)
    {
        // 搜索第一个大于 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 需要满足 Compare 且 T 需要
满足 LessThanComparable (要求严格弱序)
仅需满足划分要求;
允许异构比较
LWG 384 C++98 最多允许 log 2 (N)+1 次比较 修正为 log 2 (N)+O(1)
LWG 577 C++98 last 不可被返回 允许返回
LWG 2150 C++98 若在 [ first , last ) 中存在迭代器 iter 使得
bool ( comp ( value, * iter ) ) 为 true ,则 std::upper_bound
可能返回 [ iter , last ) 中的任意迭代器
不能返回 iter 之后的
任何迭代器

参阅

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