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) ( 설명 전용* )

key 가 가리키는 요소와 동일한 요소를 ptr 가 가리키는 배열에서 찾습니다. 배열은 count 개의 요소를 포함하며 각 요소는 size 바이트입니다. 배열은 key 가 가리키는 객체를 기준으로 분할되어야 합니다. 즉, 비교 결과 더 작은 모든 요소는 동일한 요소보다 앞에 나타나야 하고, 동일한 요소는 더 큰 요소보다 앞에 나타나야 합니다. 완전히 정렬된 배열은 이러한 요구 사항을 충족합니다. 요소들은 comp 가 가리키는 함수를 사용하여 비교됩니다.

배열이 comp 가 사용하는 동일한 기준에 따라 오름차순으로 이미 분할되지 않은 경우, 동작은 정의되지 않습니다.

배열에 검색 대상 요소와 동일하다고 comp 가 판단하는 여러 요소가 포함된 경우, 함수가 결과로서 어떤 요소를 반환할지는 명시되어 있지 않습니다.

목차

매개변수

key - 검색할 요소에 대한 포인터
ptr - 검사할 배열에 대한 포인터
count - 배열의 요소 개수
size - 배열 내 각 요소의 크기(바이트 단위)
comp - 비교 함수. 첫 번째 인자가 두 번째 인자보다 작으면 음의 정수 값을, 첫 번째 인자가 두 번째 인자보다 크면 양의 정수 값을, 인자들이 동등하면 0을 반환합니다. key 가 첫 번째 인자로, 배열의 요소가 두 번째 인자로 전달됩니다.

비교 함수의 시그니처는 다음과 동등해야 합니다:

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

이 함수는 전달된 객체를 수정해서는 안 되며, 배열 내 위치에 관계없이 동일한 객체에 대해 호출될 때 일관된 결과를 반환해야 합니다.

반환값

찾은 요소에 대한 포인터 또는 요소를 찾지 못한 경우 널 포인터.

참고 사항

이름과는 달리, C나 POSIX 표준은 이 함수가 이진 검색을 사용하여 구현되거나 어떠한 복잡도 보장을 할 것을 요구하지 않습니다.

C++ 표준 라이브러리가 제공하는 두 오버로드는 매개변수 comp 의 타입이 서로 다르기 때문에 구별됩니다 ( language linkage 는 해당 타입의 일부입니다).

예제

#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 << "value " << key;
        if (p)
            std::cout << " found at position " << (p - arr.data()) << '\n';
        else
            std::cout << " not found\n";
    }
}

출력:

value 4 found at position 3
value 8 found at position 7
value 9 not found

참고 항목

지정되지 않은 타입의 요소 범위를 정렬합니다
(함수)
특정 키와 일치하는 요소들의 범위를 반환합니다
(함수 템플릿)
C 문서 for bsearch