glib 库 hash table 使用

glib库提供了 hashtable 的实现

1. 常用函数:

创建一个 GHashTable 函数:
hash_func 是创建value的key值的函数,key_equal_func 是比较两个key是否相等的函数
GHashTable* g_hash_table_new (GHashFunc hash_func, GEqualFunc key_equal_func)

 

插入一个 key 和 value 到 GHashTable 函数:
注意:这里的key和value必须是一个独立的存储空间
void g_hash_table_insert (GHashTable *hash_table, gpointer key, gpointer value)

 

根据给定的 key 查找 value 函数:
gpointer g_hash_table_lookup (GHashTable *hash_table, gconstpointer key)
gboolean g_hash_table_lookup_extended (GHashTable *hash_table, gconstpointer lookup_key, gpointer *orig_key, gpointer *value)
 
gpointer 可以看作是一个 void* 的类型
需要特别注意:g_hash_table_new ()
参数 hash_func 和 key_equal_func 需要自己实现。在使用的时候,根据 key 的类型不同,进行相应的实现。
如果插入的时候使用了 char* 类型的 key,但是如果g_hash_table_new 中的参数用的是int类型的比较实现,
那么在 g_hash_table_lookup 的时候就会找不到value;
在glib库中已经给了实现的函数下面举例说明

2.使用举例

下面是正确的使用方法
//string类型key的比较函数
gboolean g_str_equal (gconstpointer v1, gconstpointer v2)
{
const gchar *string1 = v1;
const gchar *string2 = v2;
 
return strcmp (string1, string2) == 0;
}
 
//string类型key生成函数
guint g_str_hash (gconstpointer v)
{
/* 31 bit hash function */
const signed char *p = v; guint32 h = *p; if (h) for (p += 1; *p != '\0'; p++) h = (h << 5) - h + *p; return h; } GHashTable *ghashtbal = g_hash_table_new (g_str_hash , g_str_equal); char *key = "testkey"; char *value = "testvalue"; char *tmp = NULL; //插入的时候需要对内存 g_hash_table_insert (hash_table, strdup(key), strdup(value)); tmp = g_hash_table_lookup (hash_table, key);

 

 3.注意:
下面是错误的用法原因是 key 为字符串,但是使用了 int 型的 key 的生成函数和比较函数
//int类型key的比较函数
bool g_int_equal (void *a, void *b)
{
bool flag = false;
flag = *((const gint*) a) == *((const gint*) b);
return flag;
}

//int类型key生成函数
unsigned int g_int_hash (void *key)
{
unsigned int num = 0;
num = (unsigned int) *((const unsigned int*) key);
return num;
}
 
GHashTable *ghashtbal = g_hash_table_new (g_int_hash , g_int_equal);
char *key = "testkey";
char *value = "testvalue";
char *tmp = NULL;

//插入的时候需要对内存
g_hash_table_insert (hash_table, strdup(key), strdup(value));

//这个地方 tmp 有可能就找不到了
tmp = g_hash_table_lookup (hash_table, key);

 

 

转载于:https://www.cnblogs.com/etangyushan/p/6077307.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值