0

GLib ハッシュ テーブルを使用しています。見つけたキーの現在の値を取得して、その値をインクリメントしようとしています。既存の値をどのように置き換えることができるかよくわかりません。

 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

どんなアイデアでも大歓迎です。

4

2 に答える 2

1

g_hash_table_replaceを見ましたか?

insert と同じ引数を取るようです。
検索呼び出しは gpointer を返します。結果をguintにキャストし、インクリメントしてから、インクリメントされた値でreplaceを呼び出します。

于 2010-02-16T03:26:59.070 に答える
0
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
}
于 2010-02-16T03:39:19.540 に答える