繁体   English   中英

C中的bsearch函数和结构

[英]bsearch function and structure in C

我正在使用结构数组来存储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");
}

通常,您使用相同的功能进行排序和搜索-它可以确保搜索使用与排序相同的条件。

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

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

bsearch()qsort()使用相同的比较函数,但请记住bsearch()key应为struct student 因此,您的代码将如下所示:

struct student student_key;    // roll number to be searched

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

struct student *res = (struct student *)bsearch(&student_key, S, size, sizeof(struct student), compare);

还有最后一件事。 永远不要使用gets() 至少始终使用fgets()

bsearch提供了一个不错的例子。 您必须对qsortbsearch使用相同的比较功能,因为bsearch假定一个已排序的列表,并使用其比较功能来确定其迭代搜索过程中下一个搜索的方向。

乍一看,我认为您不需要重新定义比较功能。 您应该能够对qsortbsearch都使用compare ,实际上,如果bsearch要成功搜索qsort顺序,则这些功能必须等效。

通过首先形成struct student并使用其.id成员,代码可以使用与qsort()使用的比较函数相同的比较函数。

struct student dummy;
dummy.id = key;
struct student *res = bsearch(&dummy, S, SIZE, sizeof S[0], compare1);

另外,代码可以使用其他比较并直接使用int key

int bsearch_compare(const void* key_ptr, const void* element_ptr){
  int id1 = *((const int *)key_ptr);
  int id2 = ((const struct student *)element_ptr)->id;
  return id1 - id2;
}

struct student *res = bsearch(&key, S, SIZE, sizeof S[0], bsearch_compare);

为了获得正确的全范围int功能,请同时更改两个比较功能:

  // return id1 - id2;
  return (id1 > id2) - (id1 < id2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM