Ho bisogno di sviluppare una serie di funzioni per estendere glib2 GTreecon:
- trovare primo elemento
- trovare lo scorso
- trovare più vicino (piano, ceil, grande meno di, almeno maggiore di)
Trovare prima è facile. È sufficiente fermare il g_tree_foreach()Calback dopo la prima. Ma come trovare l'ultimo elemento , senza attraversare tutto l'albero ?
Ho pensato che avrei potuto usare g_tree_search()con un callback che continua a tornare un valore positivo fino trovato, ma come faccio a sapere che sono attualmente l'ultimo elemento?
#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;
}













