问题
I have this very simple piece of code
GTree* teste = g_tree_new(cmp);
for(int i = 0; i < 10; i++){
g_tree_insert(teste, &i, &i);
printf("%d", g_tree_nnodes(teste));
}
The "cmp" function is
int cmp(const void *a, const void* b){
int* ia = (int*)a;
int* ib = (int*)b;
return (*ia - *ib);
}
I don't understand why, but the number of nodes is always one. It seems the compare function is not being used properly, and it always asserts to 0.
回答1:
The documentation on this functions says:
If the given key already exists in the GTree its corresponding value is set to the new value. If you supplied a
value_destroy_func
when creating the GTree, the old value is freed using that function. If you supplied akey_destroy_func
when creating the GTree, the passed key is freed using that function.
So duplicate keys are not allowed. The value will just being overwritten.
You need to allocate both key and a value separately and use g_tree_new_full
to create a tree, supplying destruction functions.
So your code should look like this:
#include <glib.h>
#include <stdio.h>
int cmp(const void *a, const void *b, void *data)
{
int *ia = (int *) a;
int *ib = (int *) b;
return (*ia - *ib);
}
int main(void)
{
GTree* teste = g_tree_new_full(&cmp, NULL, &free, NULL);
for(int i = 0; i < 10; i++){
int *kv = malloc(sizeof i);
*kv = i;
g_tree_insert(teste, kv, kv);
printf("%d", g_tree_nnodes(teste));
}
putchar('\n');
g_tree_unref(teste);
}
来源:https://stackoverflow.com/questions/55424486/glib-tree-insertion-always-inserts-in-the-same-node