我认为我不理解glib2的哈希表,特别是当键和值都是整数时如何正确使用GINT_TO_POINTER。我认为这是创建新哈希表时使用 g_int_hash
和 g_int_equal
的用例。然而,下面的代码片段会出现错误。
#include <glib.h>
int main(void) {
GHashTable * freq = g_hash_table_new(g_int_hash, g_int_equal);
for (int i = 0; i < 10; i++) {
g_hash_table_insert(freq, GINT_TO_POINTER(i), GINT_TO_POINTER(0));
}
g_hash_table_destroy(freq);
}
我知道两种方法可以解决这个问题:一种是创建一个像这样的哈希表而不更改任何其他内容:
GHashTable * freq = g_hash_table_new(g_direct_hash, g_direct_equal);
第二种方法是,保持创建原样,但为键和值显式分配空间:
int * key = malloc(sizeof(int));
int * value = malloc(sizeof(int));
然后通过将其强制转换为 (gpointer) 来插入键和值。
第二种方法似乎是进行键值对的一种非常乏味的方法,这是进行int到int映射的正确方法吗?谢谢。
最佳答案
g_int_hash()
的文档说:
Note that this function acts on pointers to
gint
, not ongint
directly: if your hash table's keys are of the formGINT_TO_POINTER (n)
, useg_direct_hash()
instead.
所以,是的,如果您正在进行 int 到 int 的映射,您应该使用 g_direct_hash()
、g_direct_equal()
和 GINT_TO_POINTER()
.
关于glib2 哈希表 : GINT_TO_POINTER macro,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22057521/