GHashTable that using uint64_t as key and a struct as value

拜拜、爱过 提交于 2019-12-02 09:45:24

See in ghash.c how g_int64_hash and g_int64_equal are implemented:

...
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;
}
...

You can write your won uint64_t_hash and uint64_equal similarly:

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;
}

See an example:

#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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!