c - 使 C 比较函数对称

标签 c binary-search

C 的bsearch 比较函数有两个参数类型转换为void *。标准是否要求第一个是键,第二个是数据元素?

如果比较函数采用不同类型的键和值,这是相关的。最近看到如下代码:

typedef struct {
    unsigned int key;
    char *value;
} record;

int cmp_find(const void *val, const void *key) {
    return strcmp((char *)val, ((record *)key)->value);
}

以及具有与原始 bsearch 类似签名的自定义搜索功能。如果我使用 bsearch-compare 函数,这会发生崩溃。

标准甚至允许 bsearch - 比较具有不同值类型的函数吗?

最佳答案

是的。来自 n1570(C99+修正案/C11):

7.22.5 Searching and sorting utilities

2 The implementation shall ensure that the second argument of the comparison function (when called from bsearch), or both arguments (when called from qsort), are pointers to elements of the array.302) The first argument when called from bsearch shall equal key.

关于c - 使 C 比较函数对称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27294373/

相关文章:

c++ - 如何对 std::map 中的部分键进行二进制搜索?

c - libnfc 模拟标签类型4(14443b)

c - 如何使用 ICU4C 规范化字符串?

jquery - 只写 websocket 通信(从 HTTP 服务器到浏览器)

c - 嵌套结构中的数据如何存储和填充?

c - C 中二进制搜索的第一次和最后一次出现

c++ - 应用程序可以自行终止的最暴力方式是什么(linux)

c++ - 通过修改二进制搜索算法来改进它,使其在大量单词(单词列表)中搜索单词时工作得更快

algorithm - 矩阵的二进制搜索

java - 使用 Collections.binarySearch() 进行谓词搜索(即不完全匹配)