2013-07-25 14 views
1

如何在使用单个列表时使用g_slist_find_custom()。 列表的每个节点都是一个结构。在GLib中搜索g_slist_find_custom()函数

typedef struct { 
    int number; 
    int price; 
    char* title; 
}Books; 

GSList *list =NULL, 
g_slist_find_custom(list, /*?*/, (GCompareFunc)compp/*?*/); 

回答

1

您可以使用函数比较在GSList项目:

gint comp(gpointer p) 
{ 
    const Books *x = p; 

    return strcmp(x->title, "Don Quijote"); 
} 

item = g_slist_find_custom(list, NULL, (GCompareFunc)comp); 

gint comp(gpointer pa, gpointer pb) 
{ 
    const Books *a = pa, *b = pb; 

    /* Compares by title, but also you can compare by index or price */ 
    return strcmp(a->title, b->title); 
} 

GSList *list = NULL; 
Books temp, *item, *abook = g_malloc(sizeof(Books)); 

strcpy(abook->title, "Don Quijote"); 
list = g_slist_append(list, abook); 
/* more code */ 
temp.title = "Don Quijote"; 
item = g_slist_find_custom(list, &temp, (GCompareFunc)comp); 
/* now item contains abook */ 

此外,您可以使用NULL作为第二个参数比较常数