bsearch
来自cppreference.com
|
|
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
| 在头文件 <stdlib.h> 中定义
|
||
查找一个元素等于元素所指向的
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 <stdlib.h> #include <stdio.h> struct data { int nr; char const *value; } dat[] = { {1, "Foo"}, {2, "Bar"}, {3, "Hello"}, {4, "World"} }; int data_cmp(void const *lhs, void const *rhs) { struct data const *const l = lhs; struct data const *const r = rhs; return l->nr < r->nr; } int main(void) { struct data key = { .nr = 3 }; struct data const *res = bsearch(&key, dat, sizeof(dat)/sizeof(dat[0]), sizeof(dat[0]), data_cmp); if(!res) { printf("No %d not found\n", key.nr); } else { printf("No %d: %s\n", res->nr, res->value); } }
输出:
No 3: Hello
[编辑] 另请参阅
| 对未指定类型的多个元素进行排序 (函数) | |
| C++ documentation for bsearch
| |