Мне нужно разработать набор функций , чтобы расширить glib2 GTreeс:
- найти первый элемент
- найти последний
- найти ближайший (пол, CEIL, наибольшее меньше, меньше, чем больше)
Обнаружение первого легко. Вы просто остановить g_tree_foreach()Колбек после первого. Но как найти последний элемент без обхода всего дерева ?
Я думал , что я мог бы использовать g_tree_search()с обратным вызовом , который постоянно возвращается положительное значение , пока не найдено, но , как я знаю , что я в данный момент на последнем элементе?
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <glib.h>
static
gint compare_int(gconstpointer p1, gconstpointer p2) {
int i1 = GPOINTER_TO_INT(p1);
int i2 = GPOINTER_TO_INT(p2);
//printf(%d %d\n, i1, i2);
return i1 == i2 ? 0 : i1 > i2 ? 1 : -1;
}
static
gboolean traverse(gpointer key, gpointer value, gpointer data) {
//int ikey = GPOINTER_TO_INT(key);
const char *sval = (const char *)value;
printf(%s\n, sval);
return FALSE;
}
static
gint find_last(gconstpointer p, gpointer user_data) {
return 1;
}
static inline const char *NULS(const char *s) {
return s ? s : NULL;
}
int main(int argc, char *argv[]) {
GTree *tree = g_tree_new(compare_int);
g_tree_insert(tree, GINT_TO_POINTER(10), ten);
g_tree_insert(tree, GINT_TO_POINTER(-99), minus ninety-nine);
g_tree_insert(tree, GINT_TO_POINTER(8), eight);
g_tree_foreach(tree, traverse, NULL);
printf(=======\n%s\n, NULS((const char*)g_tree_search(tree, (GCompareFunc)find_last, NULL)));
return 0;
}













