开发者

g_tree_insert overwrites all data

开发者 https://www.devze.com 2022-12-24 13:28 出处:网络
I wonder how I should use the GTree (from GLib) to store data? Every new value I insert into GTree with g_tree_insert routine is overwrite the previous one!

I wonder how I should use the GTree (from GLib) to store data? Every new value I insert into GTree with g_tree_insert routine is overwrite the previous one!

GTree *tree; //init
tree = g_tree_new( g_str_equal ); //"g_str_equal" is a GLib default compare func
//...
for( i = 0; i < 100; ++i )
    g_tree_insert( tree, random_key(), random_value() ); //insert some random vals
//
printf( "%d", g_tree_nnodes( tree ) ); //should be 100? NO! Pr开发者_开发知识库ints "1"!!!

What am I doing wrong? Thank you.


That's because equality is not the same as comparison, g_tree_new needs a function that gives you the order of two keys (i.e. dictionary order), not just whether they are equal or not.


I think I found a solution. The problem was in the:

tree = g_tree_new( g_str_equal );

The official tutorial said it is the one of the default GCompareFunc's, so I decided to use it (by the way, I successfuly use it in the GHashTable with no problem). But it is the trouble. The correct initialization is:

tree = g_tree_new((GCompareFunc)g_ascii_strcasecmp);

And voila! It works! Thanx to IBM tutorials.

0

精彩评论

暂无评论...
验证码 换一张
取 消