std::bsearch (3) - Linux Manuals
std::bsearch: std::bsearch
NAME
Synopsis
Defined in header <cstdlib>
void* bsearch( const void* key, const void* ptr, std::size_t count,
std::size_t size, /*compare-pred*/* comp ); (1)
void* bsearch( const void* key, const void* ptr, std::size_t count,
std::size_t size, /*c-compare-pred*/* comp );
extern "C++" using /*compare-pred*/ = int(const void*, const void*); // exposition-only (2)
extern "C" using /*c-compare-pred*/ = int(const void*, const void*); // exposition-only
Finds an element equal to element pointed to by key in an array pointed to by ptr. The array contains count elements of size bytes each and must be partitioned with respect to the object pointed to by key, that is, all the elements that compare less than must appear before all the elements that compare equal to, and those must appear before all the elements that compare greater than the key object. A fully sorted array satisfies these requirements. The elements are compared using function pointed to by comp.
The behavior is undefined if the array is not already partitioned in ascending order with respect to key, according to the same criterion that comp uses.
If the array contains several elements that comp would indicate as equal to the element searched for, then it is unspecified which element the function will return as the result.
Parameters
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 - The signature of the comparison function should be equivalent to the following:
Return value
Pointer to the found element or null pointer if the element has not been found.
Notes
Despite the name, neither C nor POSIX standards require this function to be implemented using binary search or make any complexity guarantees.
The two overloads provided by the C++ standard library are distinct because the types of the parameter comp are distinct (language_linkage is part of its type)
Example
// Run this code
Output:
See also
qsort (function)
equal_range (function template)