bsearch

bsearch 搜索数组

示例如下:

 1        #include <stdio.h>
 2        #include <stdlib.h>
 3        #include <string.h>
 4 
 5        struct mi {
 6            int nr;
 7            char *name;
 8        } months[] = {
 9            { 1, "jan" }, { 2, "feb" }, { 3, "mar" }, { 4, "apr" },
10            { 5, "may" }, { 6, "jun" }, { 7, "jul" }, { 8, "aug" },
11            { 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
12        };
13 
14        #define nr_of_months (sizeof(months)/sizeof(months[0]))
15 
16        static int
17        compmi(const void *m1, const void *m2)
18        {
19            struct mi *mi1 = (struct mi *) m1;
20            struct mi *mi2 = (struct mi *) m2;
21            return strcmp(mi1->name, mi2->name);
22        }
23 
24        int
25        main(int argc, char **argv)
26        {
27            int i;
28 
29            qsort(months, nr_of_months, sizeof(struct mi), compmi);
30            for (i = 1; i < argc; i++) {
31                struct mi key, *res;
32                key.name = argv[i];
33                res = bsearch(&key, months, nr_of_months,
34                              sizeof(struct mi), compmi);
35                if (res == NULL)
36                    printf("'%s': unknown month\n", argv[i]);
37                else
38                    printf("%s: month #%d\n", res->name, res->nr);
39            }
40            exit(EXIT_SUCCESS);
41        }

(备注:示例代码来自 Linux 的 bsearch 在线帮助文档)

posted @ 2016-02-24 19:13  YBHello  阅读(221)  评论(0编辑  收藏  举报