Re: [gtk-list] glib: how to sort a doubly linked list?
- From: Eric Wong <egwong netcom com>
- To: gtk-list redhat com
- Subject: Re: [gtk-list] glib: how to sort a doubly linked list?
- Date: Mon, 1 Jun 1998 12:29:24 -0700 (PDT)
Joel Wijngaarde wrote:
>
> Hi
>
> i noticed a function in glib called:
> GList* g_list_insert_sorted (GList *list, gpointer data,
> GCompareFunc func)
[ cut ]
> Now i want to sort the GList alphabetically, looking at the 'name' in
> the data structure... Is there a way i can achieve this with the
> function above?
You could loop through the list with g_list_foreach(), copying
the data to a new list. With a little work, something like
this ought to do. One small problem is that the new list has
an empty element at the beginning (from g_list_alloc()) :( I
can't think of a simple workaround.
#include <gtk/gtk.h> /* glib's somewhere in here */
#include <string.h> /* for strcmp */
#include <stdio.h> /* for printf */
void
print_data( gpointer data, gpointer user_data )
{
printf("%s\n", (char *)data);
}
int
compare_func( gpointer a, gpointer b )
{
if ( a == NULL || b == NULL ) return 1;
return strcmp( (char *)a, (char *)b );
}
void
sort_glist( gpointer data, gpointer user_data )
{
if ( data == NULL ) return;
g_list_insert_sorted( (GList *)user_data, data, &compare_func );
}
int
main( int argc, char **argv )
{
GList *glist_old;
GList *glist_new;
glist_old = g_list_alloc(); /* make list */
glist_old->data = "foobar";
g_list_append( glist_old, "joobar" );
g_list_append( glist_old, "hoobar" );
g_list_append( glist_old, "ioobar" );
g_list_append( glist_old, "goobar" );
g_list_foreach( glist_old, &print_data, NULL );
printf("\n");
glist_new = g_list_alloc(); /* make new list */
g_list_foreach( glist_old, &sort_glist, glist_new ); /* fill new list */
g_list_foreach( glist_new, &print_data, NULL );
g_list_free( glist_old );
return 0;
}
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]