g_tree_insert 覆盖所有数据
我想知道我应该如何使用 GTree (来自 GLib)来存储数据?我使用 g_tree_insert 例程插入 GTree 的每个新值都会覆盖前一个值!
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"!!!
我做错了什么?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为相等与比较不同,
g_tree_new
需要一个函数来给出两个键的顺序(即字典顺序),而不仅仅是它们是否相等。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.我想我找到了解决方案。问题出在:
官方教程说它是默认的 GCompareFunc 之一,所以我决定使用它(顺便说一句,我成功地在 GHashTable 中使用它,没有任何问题)。但这就是麻烦。正确的初始化是:
瞧!有用!感谢 IBM 教程。
I think I found a solution. The problem was in the:
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:
And voila! It works! Thanx to IBM tutorials.