首页 > 解决方案 > C中的bsearch函数和结构

问题描述

我正在使用一组结构来存储 n 个学生的信息。这个结构数组首先使用 qsort() 函数进行排序,然后使用 bsearch() 函数在排序的结构数组中搜索卷号。我应该为 bsearch() 的比较器函数编写什么代码?

源代码:

#include<stdio.h>
#define SIZE 15

// search for a structure in array of structures using qsort() and bsearch()

struct student{
    int id;
    char name[30];
}S[SIZE];

int compare(const void* S, const void* T){
    int id1 = ((struct student *)S) -> id;
    int id2 = ((struct student *)T) -> id;

    return id1 - id2;
}

struct student comapre1(const void* S, const void* T){
    // what code should i include here
}

void main(){
    int size, i;
    printf("How many students are there ?: ");
    scanf("%d", &size);
    printf("----------------------------------------------------------\n");

    for(i = 0 ; i < size ; i++){
        printf("Student %d\nEnter roll number: ",i+1);
        scanf("%d", &S[i].id);
        while(getchar() != '\n');
        printf("Enter name: ");
        gets(S[i].name);
        printf("----------------------------------------------------------\n");
    }

    qsort(S, SIZE, sizeof(struct student), compare);        // sorting array of structues

    int key;    // roll number to be searched

    printf("Enter roll number whose record wants to be searched: ");
    scanf("%d", &key);

    struct student *res = bsearch(&key, S, SIZE, sizeof(struct student), compare1);

    if(res != NULL){    
        // display name and id of record found
    }else
        printf("not found");
}

标签: cstruct

解决方案


通常,您使用相同的函数进行排序和搜索——它保证搜索使用与排序相同的条件。

将参数传递给比较器的方式bsearch()和方式之间存在差异,有时您可以利用这种差异。qsort()例如,您可能没有完整填充的结构作为关键字传递给搜索,但用于对数据进行排序的字段也应该存在于关键字中。

在您有一个需要此类恶作剧的具体用例之前,请使用相同的比较器进行排序和搜索。


推荐阅读