c - 获取对存储在 GHashTable 中的键的引用

标签 c hashtable associative-array glib

我正在使用 glib 中的 GHashTable,我想通过键删除一个键值对。如 docs 中所述当调用 g_hash_table_remove() 时,您需要在动态分配时自行释放键和值。但是我如何获得指向 key 的指针以便释放它?

编辑:我考虑过使用 g_hash_table_new_full 但我对 GHashTable 的使用太小以至于我认为这有点矫枉过正。我宁愿手动释放 key 。

编辑:正如 Keine Lust 所指出的,g_hash_table_new_full 的性能应该不会降低。如果不需要,您还可以为其中一个销毁函数传递 NULL

最佳答案

在哈希表中删除条目时释放相关数据的一种简单方法是将free函数传递给g_hash_table_new_full:

GHashTable = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);

参数

hash_func: a function to create a hash value from a key

key_equal_func: a function to check two keys for equality

key_destroy_func: a function to free the memory allocated for the key used when removing the entry from the GHashTable, or NULL if you don't want to supply such a function.

value_destroy_func: a function to free the memory allocated for the value used when removing the entry from the GHashTable, or NULL if you don't want to supply such a function.

关于c - 获取对存储在 GHashTable 中的键的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45652771/

相关文章:

c - 为什么 printf() 在这段代码中打印出来?

powershell - 如何在powershell中检查关联数组是否为空

algorithm - 确定 Pearson 哈希的完美哈希查找表

javascript - 如何创建 Javascript 哈希表/关联数组原型(prototype)

c - 在公共(public)上下文中使用循环时需要简化逻辑

c - C 函数调用中后缀或前缀递增的未定义行为

c - 为什么对 int 的引用只返回一个内存地址?

hashtable - 具有墓碑的哈希表的负载因子

Javascript 自然排序数组/对象并维护索引关联

python - Django 数组或列表输出?