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

标签 c linux hashtable glibc

我正在研究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/

相关文章:

c - 如何在c中传递Union数组

linux - bash循环仅在最后一个文件上执行命令

hashtable - 基于磁盘的快速哈希表?

java - 自定义 HashMap 代码问题

c - 使用 sscanf 从 C 中的字符串常量中读取单个字符

c - Linux 字符设备驱动程序如何检测使用它的程序何时异常退出?

C 函数参数

linux - 了解 linux 内核和补丁发布

c++ - 将进程的输出写入缓冲区

powershell - 根据列表替换 PSObj 属性值