如何清空GLib树?

时间:2018-05-14 15:57:42

标签: c glib

为了清空GLib树,必须首先遍历树并填充所有找到的键的列表。然后可以使用g_tree_remove函数清空树。问题是我不知道如何从遍历函数填充列表。这就是我试过的

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

//Prototypes
gint treeCompareFunction (const gchar* a, const gchar* b, gpointer self);
gboolean traverseTree(gpointer key, gpointer value, gpointer data);

int main()
{
    GTree* tree = g_tree_new_full ((GCompareDataFunc) treeCompareFunction, NULL, NULL, NULL);
    // Insert data into the tree
    g_tree_insert (tree, "key 1", "val 1");
    g_tree_insert (tree, "key 2", "val 2");
    g_tree_insert (tree, "key 3", "val 3");

    GSList* list = NULL;
    // Try to get all the keys of the tree in a list
    g_tree_foreach (tree, (GTraverseFunc)traverseTree, list);
    printf ("List size after tree traversal: %"  G_GUINT32_FORMAT "\n", g_slist_length(list));
    //TODO empty the tree
    return 0;
}

gint treeCompareFunction (const gchar* a, const gchar* b, gpointer self) {
    return g_strcmp0(a, b);
}

gboolean traverseTree(gpointer key, gpointer value, gpointer data) {
 data = g_slist_append(data, key);
 printf ("List size in traversal function: %"  G_GUINT32_FORMAT "\n", g_slist_length(data));
 return FALSE;
}

输出

List size in traversal function: 1
List size in traversal function: 1
List size in traversal function: 1
List size after tree traversal: 0

如何获取列表中的所有密钥然后清空树?

1 个答案:

答案 0 :(得分:1)

您需要将指针传递给GSList*,而不是GSList*本身,否则遍历函数正在修改指向列表头部的本地指针,而不是指向头部的指针。列表main()

GSList *list = NULL;
g_tree_foreach (tree, (GTraverseFunc)traverseTree, &list);
…

gboolean traverseTree(gpointer key, gpointer value, gpointer data) {
 GSList *out_list = data;
 *out_list = g_slist_append(*out_list, key);
 printf ("List size in traversal function: %"  G_GUINT32_FORMAT "\n", g_slist_length(*out_list));
 return FALSE;
}

另外,请注意,使用g_slist_append()迭代地附加到链接列表将为您提供O(N ^ 2)性能,并且g_slist_length()需要O(N)时间。使用指针数组总体上会更容易,更有效:

GPtrArray *items_to_remove = g_ptr_array_sized_new (g_tree_nnodes (tree));
g_tree_foreach (tree, (GTraverseFunc)traverseTree, items_to_remove);
…

gboolean traverseTree(gpointer key, gpointer value, gpointer data) {
 GPtrArray *items_to_remove = data;
 g_ptr_array_add(items_to_remove, key);
 printf ("List size in traversal function: %u\n", items_to_remove->len);
 return FALSE;
}