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 | - | 比较函数。若首个参数小于第二个,则返回负整数值,若首个参数大于第二个,则返回正整数值,若两参数相等,则返回零。 key is passed as the first argument, an element from the array as the second.比较函数的签名应等价于如下形式: int cmp(const void *a, const void *b); 该函数必须不修改传递给它的对象,而且在调用比较相同对象时必须返回一致的结果,无关乎它们在数组中的位置。 |
[编辑] 返回值
指针指向的元素或以其他方式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 (函数) | |
| 返回匹配特定键值的元素区间 (函数模板) | |
| bsearch的 C 文档
| |