Namespaces
Variants
Views
Actions

std::bsearch

From cppreference.com
< cpp‎ | algorithm
Revision as of 12:17, 9 January 2013 by Cubbi (Talk | contribs)

 
 
 

Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <cstdlib>
</td>

<td></td> <td></td> <tr class="t-dcl ">

<td class="t-dcl-nopad">
void* bsearch( const void* key, const void* ptr, size_t count, size_t size,
               int (*comp)(const void*, const void*) );
</td>

<td class="t-dcl-nopad"> </td> <td class="t-dcl-nopad"> </td> </tr> Template:ddcl list end

Finds an element equal to element pointed to by key in an array pointed to by ptr. The array contains count elements of size size. Function pointed to by comp is used for object comparison.

Contents

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 - 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.

Return value

Pointer to the found element or NULL otherwise.

Example

#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";
}

Output:

value 4 found at position 3
value 9 not found

See also

Template:cpp/algorithm/dcl list qsortTemplate:cpp/algorithm/dcl list equal range
C documentation for bsearch