std::bsearch
来自cppreference.com
|
|
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
| 在头文件 <cstdlib> 中定义
|
||
| void* bsearch( const void* key, const void* ptr, size_t count, size_t size, int (*comp)(const void*, const void*) ); |
||
查找一个元素等于元素所指向的
key中指出,ptr的阵列。该数组包含count元素的大小size。功能指向的对象比较comp用于.原文:
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.目录 |
[编辑] 参数
| key | - | 要搜索的元素的指针
原文: pointer to the element to search for |
| ptr | - | 指针的数组检查
|
| count | - | 数组中的元素的数量
|
| 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. int cmp(const void *a, const void *b); The function must not modify the objects passed to it. |
[编辑] 返回值
指针指向的元素或以其他方式NULL.
原文:
Pointer to the found element or NULL otherwise.
[编辑] 示例
#include <cstdlib> #include <iostream> int compare(const void *ap, const void *bp) { const int *a = (int *) ap; const int *b = (int *) bp; return *a - *b; } int show_ptr(int *p) { if (p == NULL) { std::cout << "NULL\n"; } else { std::cout << p1 << ' ' << *p1 << '\n'; } } 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); int key2 = 9; int *p2 = (int *) std::bsearch(&key2, arr, ARR_SIZE, sizeof(arr[0]), compare); std::cout << "p1: "; show_ptr(p1); std::cout << "p2: "; show_ptr(p2); }
输出:
p1: 0xbf9a4c88 4 p2: NULL
[编辑] 另请参阅
| 排序范围内的未指定类型的元素 原文: sorts a range of elements with unspecified type (函数) | |
| 返回匹配特定键值的元素区间 (函数模板) | |
| C语言文档 for bsearch
| |