Namespaces
Variants

std:: bsearch

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)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
bsearch
Numeric operations
Operations on uninitialized memory
定义于头文件 <cstdlib>
void * bsearch ( const void * key, const void * ptr, std:: size_t count,

std:: size_t size, /* c-compare-pred */ * comp ) ;
void * bsearch ( const void * key, const void * ptr, std:: size_t count,

std:: size_t size, /* compare-pred */ * comp ) ;
(1)
extern "C" using /* c-compare-pred */ = int ( const void * , const void * ) ;
extern "C++" using /* compare-pred */ = int ( const void * , const void * ) ;
(2) ( 仅用于说明* )

在由 ptr 指向的数组中查找与 key 所指向元素相等的元素。该数组包含 count 个元素,每个元素大小为 size 字节,且必须相对于 key 所指向的对象进行分区——即所有比较结果小于关键对象的元素必须出现在等于关键对象的元素之前,而这些又必须出现在所有比较结果大于关键对象的元素之前。完全排序的数组满足这些要求。使用 comp 所指向的函数对元素进行比较。

如果数组尚未按照与 comp 所用相同准则进行升序分区,则行为未定义。

如果数组中包含多个元素,这些元素在 comp 的比较下与要查找的元素相等,那么函数将返回哪个元素作为结果是不确定的。

目录

参数

key - 指向要查找的元素的指针
ptr - 指向要检查的数组的指针
count - 数组中的元素数量
size - 数组中每个元素的字节大小
comp - 比较函数,若第一个参数 小于 第二个参数则返回负整数值,若第一个参数 大于 第二个参数则返回正整数值,若参数等价则返回零。 key 作为第一个参数传递,数组元素作为第二个参数。

比较函数的签名应等价于以下形式:

int cmp ( const void * a, const void * b ) ;

函数不得修改传递给它的对象,并且在为相同对象调用时必须返回一致的结果,无论它们在数组中的位置如何。

返回值

指向找到的元素的指针,若未找到该元素则为空指针。

注释

尽管名称如此,C语言和POSIX标准均未要求此函数必须通过二分查找实现,也未对其复杂度作出任何保证。

C++标准库提供的两个重载之所以不同,是因为参数 comp 的类型不同( 语言链接 是其类型的一部分)。

示例

#include <array>
#include <cstdlib>
#include <iostream>
template<typename T>
int compare(const void *a, const void *b)
{
    const auto &arg1 = *(static_cast<const T*>(a));
    const auto &arg2 = *(static_cast<const T*>(b));
    const auto cmp = arg1 <=> arg2;
    return cmp < 0 ? -1
        :  cmp > 0 ? +1
        :  0;
}
int main()
{
    std::array arr{1, 2, 3, 4, 5, 6, 7, 8};
    for (const int key : {4, 8, 9})
    {
        const int* p = static_cast<int*>(
            std::bsearch(&key,
                arr.data(),
                arr.size(),
                sizeof(decltype(arr)::value_type),
                compare<int>));
        std::cout << "值 " << key;
        if (p)
            std::cout << " 在位置 " << (p - arr.data()) << " 处找到\n";
        else
            std::cout << " 未找到\n";
    }
}

输出:

值 4 在位置 3 处找到
值 8 在位置 7 处找到
值 9 未找到

参见

对未指定类型的元素范围进行排序
(函数)
返回匹配特定键的元素范围
(函数模板)
C 文档 关于 bsearch