bsearch函數解析

來源:互聯網
上載者:User

函數格式:

void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void ));

函數功能:

      將key在一系列base表示的資料中進行挨個比較,base中每個資料的大小是size,

       base中的資料總的個數是nmemb = sizeof(base)/sizeof(base[0]);

     compar 函數提供給使用者的介面,對所需的內容進行比較。compar會返回一個值,表示比較的結果,如果返回0,bsearch函數立即返回,並且返回在base中找到的位置資訊,如果到最後都沒有找到,則返回null。

函數心得:

   該函數提供了複雜尋找,減輕了我們在編程中經常遇到資料尋找需要編寫大量代碼,同樣會出現很多代碼冗餘, 效率不高的情況

函數樣本:

     #include <stdio.h>
       #include <stdlib.h>
       #include <string.h>

       struct mi {
            int nr;
            char *name;
       } months[] = {
            { 1, "jan" }, { 2, "feb" }, { 3, "mar" }, { 4, "apr" },
            { 5, "may" }, { 6, "jun" }, { 7, "jul" }, { 8, "aug" },
            { 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
       };

       #define nr_of_months (sizeof(months)/sizeof(months[0]))

       static int compmi(const void *m1, const void *m2) {
            struct mi *mi1 = (struct mi *) m1;
            struct mi *mi2 = (struct mi *) m2;
            return strcmp(mi1->name, mi2->name);
       }

       int main(int argc, char **argv) {
            int i;

            qsort(months, nr_of_months, sizeof(struct mi), compmi);
            for (i = 1; i < argc; i++) {
                 struct mi key, *res;
                 key.name = argv[i];
                 res = bsearch(&key, months, nr_of_months,
                            sizeof(struct mi), compmi);
                 if (res == NULL)
                      printf("’%s’: unknown month/n", argv[i]);
                 else
                      printf("%s: month #%d/n", res->name, res->nr);
            }
            return 0;
       }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.