c中的哈希表更新值
问题描述:
我使用Glib作为哈希表。我需要更新密钥的价值。有没有一种方法没有删除并插入哈希表进行更新。c中的哈希表更新值
我发现g_hash_table_replace()
gboolean
g_hash_table_replace (GHashTable *hash_table,
gpointer key,
gpointer value);
是从键此更新值,如果是我怎么可以使用此功能。
解决:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <glib.h>
GHashTable * hash_operation = NULL;
int main(int argc, char *argv[]) {
char *from;
int gg = 3;
char *a=strdup("32"),*b=strdup("24"),*c=("mübarek");
hash_operation = g_hash_table_new(g_str_hash, g_str_equal);
g_hash_table_insert(hash_operation, a, gg);
from = strdup(g_hash_table_lookup(hash_operation, a));
printf("%s\n",from);
g_hash_table_replace (hash_operation, a,c);
from = strdup(g_hash_table_lookup(hash_operation, a));
printf("%s\n",from);
free(a);
free(b);
free(c);
free(from);
return 0;
}
问题解决了。
答
功能g_hash_table_replace
的用法很简单:
它需要3个参数:
-
hash_table
:当然,你哈希表,所以你的情况hash_operation
-
key
:关键你想编辑。 (我相信你的关键是a
) -
value
:应该在key
一个简单的例子可以存储在GHashTable将是值:
GHashTable *table = g_hash_table_new(g_str_hash, g_str_equal);
gchar *key = "key1";
g_hash_table_insert(table, key, "Hello");
g_hash_table_replace(table, key, "World");
gchar *result = (gchar*) g_hash_table_lookup(table, key);
g_print("Result: %s\n", result); //Prints: "Result: World"
+0
哦,我错过了在你的问题'解决';反正......) – mame98
到底是什么问题了吗?喜欢,为什么你不能使用该功能(请显示您尝试的代码)?或者是该功能不适合,为什么? – hyde