Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top