GHashTable使用uint64_t作为键,使用struct作为值

时间:2014-08-14 00:33:02

标签: c linux hashtable glibc

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

1 个答案:

答案 0 :(得分:1)

请参阅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;
}