哈希 table 更新 c 中的值
Hash table update value in c
我正在使用 Glib 进行哈希 table。我需要从键更新值。有没有办法不删除和插入哈希 table 更新。
我找到了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
:应该存储在GHashTable中的值key
一个简单的例子是:
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"
我正在使用 Glib 进行哈希 table。我需要从键更新值。有没有办法不删除和插入哈希 table 更新。
我找到了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
:应该存储在GHashTable中的值key
一个简单的例子是:
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"