, M. Oehm, , ( 0). , , 0 , ( ) .
, , qsort bsearch / . :
struct foo_pair {
int key;
char *value;
};
int foo_pair_compare(void *x, void *y) {
struct foo_pair *a = x, *b = y;
return (a->key > b->key) - (a->key < b->key);
}
int main(void) {
struct foo_pair foo[] = { { .key = 3, .value = "foo" },
{ .key = 5, .value = "bar" },
{ .key = 6, .value = "etc" } };
qsort(foo, sizeof foo / sizeof *foo, sizeof *foo, foo_pair_compare);
struct foo_pair *selection = bsearch(&(struct foo_pair) { .key = 5 },
foo, sizeof foo / sizeof *foo,
sizeof *foo, foo_pair_compare);
}
When items are usually added or removed from the collection, it makes sense to choose a hash table or some sort of ordered map. If you cannot worry about writing and testing your own collections, I think there are many tried and tested libraries on the Internet that you could check.
source
share