我们如何在代码中使用 hash.h?我想编写一个快速哈希表,它接受一个 double 并输出一个指针。是否可以使用它。我没有在其中看到任何与哈希相关的常用例程。
索罕
最佳答案
看来您想要的是一个内部使用散列函数的基于 map 的数据结构。 hash.h
只提供后者,但有一些库可以为您提供数据结构。使用 libHX(在所有主要 Linux 发行版中都可用)将 double 值映射到指针(为简洁起见省略错误处理)的示例,使用特定的哈希函数:
#include <stdio.h>
#include <libHX/map.h>
static unsigned long linux_hash(const void *p, size_t chars)
{
// replace return 0 by algorithm from hash.h
return 0;
}
static const struct HXmap_ops ops = {
.k_hash = linux_hash,
};
int main(void)
{
struct HXmap *map;
double i;
map = HXmap_init5(HXMAPT_DEFAULT, HXMAP_CKEY, &ops, sizeof(double), 0);
i = 3.141;
HXmap_add(map, &i, main);
i = 3.141/2;
HXmap_add(map, &i, map);
i = 3.141;
printf("3.141 maps to %p\n", HXmap_get(map, &i));
i = 3.141/2;
printf("pi/2 maps to %p\n", HXmap_get(map, &i));
return 0;
}
当没有指定 k_hash 时,jenkins3 将被用作合理的默认值。 Linux 的 hash.h
中的散列函数看起来非常小,可能无法提供良好的特性。
关于c - Linux hash.h : Using the fast hashing routine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4959425/