GLib树插入始终插入同一节点 [英] GLib tree insertion always inserts in the same node

查看:99
本文介绍了GLib树插入始终插入同一节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段非常简单的代码

I have this very simple piece of code

GTree* teste = g_tree_new(cmp);

  for(int i = 0; i < 10; i++){
    g_tree_insert(teste, &i, &i);
    printf("%d", g_tree_nnodes(teste));
  }

"cmp"功能是

int cmp(const void *a, const void* b){
  int* ia = (int*)a;
  int* ib = (int*)b;
  return (*ia - *ib);
}

我不明白为什么,但是节点数始终是一个.似乎比较函数未正确使用,并且始终断言为0.

I don't understand why, but the number of nodes is always one. It seems the compare function is not being used properly, and it always asserts to 0.

推荐答案

如果给定的键已经存在于GTree中,则其对应的值将设置为新值.如果在创建GTree时提供了value_destroy_func,则使用该函数释放旧值.如果在创建GTree时提供了key_destroy_func,则使用该函数释放所传递的密钥.

If the given key already exists in the GTree its corresponding value is set to the new value. If you supplied a value_destroy_func when creating the GTree, the old value is freed using that function. If you supplied a key_destroy_func when creating the GTree, the passed key is freed using that function.

因此,不允许重复的密钥.该值将被覆盖.

So duplicate keys are not allowed. The value will just being overwritten.

您需要分别分配键和值,并使用g_tree_new_full创建树,提供破坏函数.

You need to allocate both key and a value separately and use g_tree_new_full to create a tree, supplying destruction functions.

因此您的代码应如下所示:

So your code should look like this:

#include <glib.h>
#include <stdio.h>

int cmp(const void *a, const void *b, void *data)
{
  int *ia = (int *) a;
  int *ib = (int *) b;
  return (*ia - *ib);
}

int main(void)
{
    GTree* teste = g_tree_new_full(&cmp, NULL, &free, NULL);

    for(int i = 0; i < 10; i++){
        int *kv = malloc(sizeof i);
        *kv = i;
        g_tree_insert(teste, kv, kv);
        printf("%d", g_tree_nnodes(teste));
    }

    putchar('\n');
    g_tree_unref(teste);
}

这篇关于GLib树插入始终插入同一节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆