命名空间
变体
操作

std::upper_bound

来自 cppreference.cn
< cpp‎ | algorithm
 
 
算法库
约束算法和范围上的算法 (C++20)
约束算法,例如 ranges::copy, ranges::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 );
(constexpr since C++20)
(until 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 );
(since C++26)
(2)
template< class ForwardIt, class T, class Compare >

ForwardIt upper_bound( ForwardIt first, ForwardIt last,

                       const T& value, Compare comp );
(constexpr since C++20)
(until 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 );
(since C++26)

在已划分范围 [firstlast) 中搜索第一个排序在 value 之后的元素。

1) 顺序由 operator< 确定

返回范围 [firstlast) 中第一个使 bool(value < *iter)true 的迭代器 iter,如果不存在这样的 iter 则返回 last

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

(until C++20)

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

(since C++20)
2) 顺序由 comp 确定
返回范围 [firstlast) 中第一个使 bool(comp(value, *iter))true 的迭代器 iter,如果不存在这样的 iter 则返回 last
如果范围 [firstlast) 的元素 elem 没有根据表达式 bool(comp(value, elem)) 进行划分,则行为未定义。

目录

[编辑] 参数

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

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

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

虽然签名不需要有 const &,但函数不得修改传递给它的对象,并且必须能够接受类型(可能为 const) Type1Type2 的所有值,而与值类别无关(因此,不允许使用 Type1 &,除非对于 Type1,移动等价于复制,否则也不允许使用 Type1(自 C++11 起))。
类型 Type1 必须使得类型 T 的对象可以隐式转换为 Type1。类型 Type2 必须使得类型 ForwardIt 的对象可以被解引用,然后隐式转换为 Type2。 ​

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

[编辑] 返回值

指向范围 [firstlast) 中排序在 value 之后的第一个元素的迭代器,如果未找到此类元素则返回 last

[编辑] 复杂度

给定 Nstd::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) 是良构的。

特性测试 Std 特性
__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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 270 C++98 Compare 需要满足 Compare,并且 T 需要是
LessThanComparable (需要严格弱序)
仅需要划分;
允许异构比较
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))true,则 std::upper_bound
可以返回 [iterlast) 中的任何迭代器
不能返回 iter 之后的迭代器
iter 可以被返回

[编辑] 参见

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