函數格式:
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;
}