开发者

Glib hash table replace

I'm using GLib Hash Table. I'm trying to get the current value of t开发者_开发知识库he key that I found and then increment its value. I'm not quite sure how can I replace the existing value.

 typedef struct {
   gchar *key;
   guint my_int;
 } my_struct;

char *v;
v = g_hash_table_lookup(table, my_struct.key);
if (v == NULL) 
   g_hash_table_insert(table, g_strdup(my_struct.key), (gpointer)(my_struct.my_int));
else 
   g_hash_table_replace() // here I'd like to do something like current_val+1

Any ideas will be appreciate it.


Did you look at g_hash_table_replace?

It appears to take the same arguments as insert.
The lookup call returns you a gpointer. You will want to cast the result to a guint, increment, and then call replace with the incremented value.


g_hash_table_replace(table, my_struct.key, v + 1)

However, to match your struct, v should be a guint, not a char * .

But note that the casting you're doing is not a good idea, as integers are not guaranteed to fit in pointers. It would be better to do something like:

 typedef struct {
   gchar *key;
   guint *my_int;
 } my_struct;

guint *v;
v = (guint*) g_hash_table_lookup(table, my_struct.key);
if (v == NULL) 
{
   my_struct.my_int = g_malloc(sizeof(guint));
   *(my_struct.my_int) = 0;
   g_hash_table_insert(table, my_struct.key, my_struct.my_int);
}
else 
{
   (*v)++;
   g_hash_table_replace(table, my_struct.key, v) // here I'd like to do something like current_val+1
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜