Namespaces
Variants

std:: binary_search

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)
binary_search
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 >

bool binary_search ( 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 bool binary_search ( ForwardIt first, ForwardIt last,

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

bool binary_search ( 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 bool binary_search ( ForwardIt first, ForwardIt last,

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

检查在已分区范围 [ first , last ) 内是否出现与 value 等效的元素。

1) 等价性检查使用 operator <

若在 [ first , last ) 中存在迭代器 iter 使得 ! bool ( * iter < value ) && ! bool ( value < * iter ) true ,则返回 true 。否则返回 false

若满足以下任意条件,则行为未定义:

  • 对于 [ first , last ) 中的任意元素 elem bool ( elem < value ) 不蕴含 ! bool ( value < elem )
  • [ first , last ) 中的元素 elem 未按表达式 bool ( elem < value ) ! bool ( value < elem ) 进行 划分
(C++20 前)

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

(C++20 起)
2) 等价性检查使用 comp 进行:
如果在 [ first , last ) 范围内存在某个迭代器 iter 使得 ! bool ( comp ( * iter, value ) ) && ! bool ( comp ( value, * iter ) ) true ,则返回 true 。否则返回 false
若满足以下任意条件,则行为未定义:
  • 对于范围 [ first , last ) 中的任何元素 elem bool ( comp ( elem, value ) ) 不蕴含 ! bool ( comp ( value, elem ) )
  • 范围 [ first , last ) 中的元素 elem 未针对表达式 bool ( comp ( elem, value ) ) ! 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 Type2 必须满足: T 类型的对象能隐式转换到这两个类型,且 ForwardIt 类型的对象在解引用后能隐式转换到这两个类型。 ​

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

返回值

当找到与 value 等价的元素时返回 true ,否则返回 false

复杂度

给定 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::binary_search 仅要求 [ first , last ) 区间被划分,但该算法通常用于 [ first , last ) 已排序的情况,如此二分搜索对任意 value 均有效。

std::binary_search 仅检查是否存在等价元素。若要获取指向该元素的迭代器(如果存在),应改用 std::lower_bound

功能测试 标准 功能
__cpp_lib_algorithm_default_value_type 202403 (C++26) 列表初始化 用于算法 ( 1,2 )

可能的实现

另请参阅 libstdc++ libc++ 中的实现。

binary_search (1)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type>
bool binary_search(ForwardIt first, ForwardIt last, const T& value)
{
    return std::binary_search(first, last, value, std::less{});
}
binary_search (2)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type,
         class Compare>
bool binary_search(ForwardIt first, ForwardIt last, const T& value, Compare comp)
{
    first = std::lower_bound(first, last, value, comp);
    return (!(first == last) and !(comp(value, *first)));
}

示例

#include <algorithm>
#include <cassert>
#include <complex>
#include <iostream>
#include <vector>
int main()
{
    const auto haystack = {1, 3, 4, 5, 9};
    for (const auto needle : {1, 2, 3})
    {
        std::cout << "正在搜索 " << needle << '\n';
        if (std::binary_search(haystack.begin(), haystack.end(), needle))
            std::cout << "已找到 " << needle << '\n';
        else
            std::cout << "未找到!\n";
    }
    using CD = std::complex<double>;
    std::vector<CD> nums{{1, 1}, {2, 3}, {4, 2}, {4, 3}};
    auto cmpz = [](CD x, CD y){ return abs(x) < abs(y); };
    #ifdef __cpp_lib_algorithm_default_value_type
        assert(std::binary_search(nums.cbegin(), nums.cend(), {4, 2}, cmpz));
    #else
        assert(std::binary_search(nums.cbegin(), nums.cend(), CD{4, 2}, cmpz));
    #endif
}

输出:

正在搜索 1
已找到 1
正在搜索 2
未找到!
正在搜索 3
已找到 3

缺陷报告

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

缺陷报告 应用于 发布时行为 正确行为
LWG 270 C++98 Compare 需要满足 Compare T 需要
LessThanComparable (要求严格弱序)
仅需满足划分要求;
允许异构比较
LWG 787 C++98 最多允许 log 2 (N)+2 次比较 修正为 log 2 (N)+O(1)

参见

返回匹配特定键的元素范围
(函数模板)
返回指向第一个 不小于 给定值的元素的迭代器
(函数模板)
返回指向第一个 大于 某值的元素的迭代器
(函数模板)
确定元素是否存在于部分有序范围内
(算法函数对象)