list: Add list_seq_find.

Sometimes one has to traverse a list to find out if some data already
exists there in order to avoid dupilcates in the list, and this function
facilitates in that without requiring that the data is ordered.
This commit is contained in:
S. Christoffer Eliesen 2015-11-18 21:12:20 +01:00
parent 56e80c0f73
commit a33e3badad
2 changed files with 13 additions and 0 deletions

View file

@ -53,3 +53,13 @@ void list_cat(list_t *list, list_t *source) {
void list_sort(list_t *list, int compare(const void *left, const void *right)) { void list_sort(list_t *list, int compare(const void *left, const void *right)) {
qsort(list->items, list->length, sizeof(void *), compare); qsort(list->items, list->length, sizeof(void *), compare);
} }
int list_seq_find(list_t *list, int (*cmp)(const void *item, const void *data), const void *data) {
for (int i = 0; i < list->length; i++) {
void *item = list->items[i];
if ((cmp)(item, data) == 0) {
return i;
}
}
return -1;
}

View file

@ -15,5 +15,8 @@ void list_del(list_t *list, int index);
void list_cat(list_t *list, list_t *source); void list_cat(list_t *list, list_t *source);
// See qsort // See qsort
void list_sort(list_t *list, int compare(const void *left, const void *right)); void list_sort(list_t *list, int compare(const void *left, const void *right));
// Return index for first item in list that returns 0 for given compare
// function or -1 if none matches.
int list_seq_find(list_t *list, int compare(const void *item, const void *cmp_to), const void *cmp_to);
#endif #endif