views:

19

answers:

2

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! Prints "1"!!!

What am I doing wrong? Thank you.

A: 

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.

pechenie
I was wrong. "g_str_equal" is GEqualFunc, but I need GCompareFunc, so there is a mistake. Thanx to everyone, I hope it helps someone!
pechenie
A: 

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.

Paul Betts
Yeah, I already discovered it by myself, but thanks anyway! Take the "correct answer" :)
pechenie
Very true, good work - I just wanted that it made more sense to people, rather than it being 'say these magic words instead'
Paul Betts