gpt4 book ai didi

c - 使用 uint64_t 作为键和结构作为值的 GHashTable

转载 作者:太空宇宙 更新时间:2023-11-04 11:05:54 24 4
gpt4 key购买 nike

我正在研究GHashTable。虽然 Stackoverflow 中已经有一些示例,但它们只是一些常见的情况。所以我仍然不确定如何实现我的要求并决定寻求帮助。
我想使用 uint64_t 作为键,使用 struct 作为值。我发现GLib中没有这样的内置哈希函数。只有一个 g_int64_hash()。虽然 key 是 uint64_t,但它只有 52 位左右。所以我认为 gint64 是可以的。但我看到一些示例使用 GINT_TO_POINTER() 来转换值(有时它们没有)。所以对此感到困惑。
非常感谢!

最佳答案

参见ghash.c g_int64_hashg_int64_equal 是如何实现的:

...
gboolean
g_int64_equal (gconstpointer v1,
gconstpointer v2)
{
return *((const gint64*) v1) == *((const gint64*) v2);
}
...
guint
g_int64_hash (gconstpointer v)
{
return (guint) *(const gint64*) v;
}
...

您可以类似地编写您的 uint64_t_hashuint64_equal:

gboolean
uint64_t_equal (gconstpointer v1,
gconstpointer v2)
{
return *((const uint64_t*) v1) == *((const uint64_t*) v2);
}

guint
uint64_t_hash (gconstpointer v)
{
return (guint) *(const uint64_t*) v;
}

看一个例子:

#include <glib.h>
#include <stdio.h>
#include <inttypes.h>

/* the value structure */
typedef struct __MyStruct
{
int a;
int b;
} MyStruct;

/* the hash equality function */
static gboolean
uint64_t_equal (gconstpointer v1,
gconstpointer v2)
{
return *((const uint64_t*) v1) == *((const uint64_t*) v2);
}

/* the hash function */
static guint
uint64_t_hash (gconstpointer v)
{
return (guint) *(const uint64_t*) v;
}

/* the hash function */
static void
print_hash(gpointer key,
gpointer value,
gpointer user_data)
{
printf("%" PRIu64 " = {%d, %d}\n",
*(uint64_t*) key, ((MyStruct *) value)->a, ((MyStruct *) value)->b);
}

int
main(int argc, char **argv)
{
GHashTable *hash;

/* key => value */
uint64_t k1 = 11; MyStruct s1 = {1, 11};
uint64_t k2 = 22; MyStruct s2 = {2, 22};
uint64_t k3 = 33; MyStruct s3 = {3, 33};

hash = g_hash_table_new(uint64_t_hash, uint64_t_equal);

/* insert values */
g_hash_table_insert(hash, &k1, &s1);
g_hash_table_insert(hash, &k2, &s2);
g_hash_table_insert(hash, &k3, &s3);

/* iterate over the values in the hash table */
g_hash_table_foreach(hash, print_hash, NULL);
g_hash_table_destroy(hash);
return 0;
}

关于c - 使用 uint64_t 作为键和结构作为值的 GHashTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25298327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com