首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::bsearch

Defined in header <cstdlib>

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

(1)

extern "C++" using /*compare-pred*/ = int(const void*, const void*); // exposition-only extern "C" using /*c-compare-pred*/ = int(const void *, const void *); // exposition-only

(2)

查找与key在指向的数组中ptr数组包含count元素size每个字节,并且必须相对于所指向的对象进行分区。key,即,所有比较小于必须出现在所有比较等于的元素之前的元素,以及那些比键对象大的所有元素前面的元素。一个完全排序的数组满足了这些要求。使用comp...

如果数组尚未按键的升序进行分区,则行为未定义。comp使用。

如果数组包含以下几个元素comp将指示为等于搜索的元素,然后未指定函数将返回哪个元素作为结果。

参数

key

-

pointer to the element to search for

ptr

-

pointer to the array to examine

count

-

number of element in the array

size

-

size of each element in the array in bytes

comp

-

comparison function which returns ​a negative integer value if the first argument is less than the second, a positive integer value if the first argument is greater than the second and zero if the arguments are equal. key is passed as the first argument, an element from the array as the second. The signature of the comparison function should be equivalent to the following: int cmp(const void *a, const void *b); The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array. ​

返回值

指向已查找元素的指针,如果未找到元素,则为空指针。

注记

尽管名称如此,但C和POSIX标准都不要求使用二进制搜索来实现该函数,也不需要提供任何复杂性保证。

C++标准库提供的两个重载是不同的,因为参数的类型comp分别为%28语言链接是其类型%29的一部分。

二次

代码语言:javascript
复制
#include <cstdlib>
#include <iostream>
 
int compare(const void *ap, const void *bp)
{
    const int *a = (int *) ap;
    const int *b = (int *) bp;
    if(*a < *b)
        return -1;
    else if(*a > *b)
        return 1;
    else
        return 0;
}
 
int main(int argc, char **argv)
{
    const int ARR_SIZE = 8;
    int arr[ARR_SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8 };
 
    int key1 = 4;
    int *p1 = (int *) std::bsearch(&key1, arr, ARR_SIZE, sizeof(arr[0]), compare);
    if(p1)
        std::cout << "value " << key1 << " found at position " << (p1 - arr) << '\n';
     else
        std::cout << "value " << key1 << " not found\n";
 
    int key2 = 9;
    int *p2 = (int *) std::bsearch(&key2, arr, ARR_SIZE, sizeof(arr[0]), compare);
    if(p2)
        std::cout << "value " << key2 << " found at position " << (p2 - arr) << '\n';
     else
        std::cout << "value " << key2 << " not found\n";
}

二次

产出:

二次

代码语言:javascript
复制
value 4 found at position 3
value 9 not found

二次

另见

qsort

sorts a range of elements with unspecified type (function)

equal_range

returns range of elements matching a specific key (function template)

c搜索文档

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券