g_tree_insert 覆盖所有数据

发布于 2024-08-26 22:24:08 字数 425 浏览 5 评论 0原文

我想知道我应该如何使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怀里藏娇 2024-09-02 22:24:08

这是因为相等与比较不同,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.

清泪尽 2024-09-02 22:24:08

我想我找到了解决方案。问题出在:

tree = g_tree_new( g_str_equal );

官方教程说它是默认的 GCompareFunc 之一,所以我决定使用它(顺便说一句,我成功地在 GHashTable 中使用它,没有任何问题)。但这就是麻烦。正确的初始化是:

tree = g_tree_new((GCompareFunc)g_ascii_strcasecmp);

瞧!有用!感谢 IBM 教程。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文