我正在使用一系列结构来存储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");
}发布于 2018-10-17 17:08:09
对key和qsort()都使用相同的比较函数,但是要记住, bsearch() 的qsort()应该是 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() 至少.
发布于 2018-10-17 16:59:38
通常,您使用相同的函数进行排序和搜索--它保证搜索使用与排序相同的条件。
bsearch()和qsort()在将参数传递给比较器的方式上存在差异,有时您可以利用这种差异。例如,您可能没有一个完全填充的结构作为搜索的键,但是用于排序数据的字段也应该出现在键中。
除非您有一个具体的用例需要这样的恶作剧,否则请使用相同的比较器进行排序和搜索。
发布于 2018-10-17 16:52:43
bsearch提供了一个不错的例子。您必须对qsort和bsearch使用相同的比较函数,因为bsearch假设排序列表,并使用其比较函数来决定迭代搜索过程中下一次搜索的方向。
乍一看,我不认为您需要重新定义您的比较函数。您应该能够将compare用于qsort和bsearch,实际上,如果bsearch要成功地搜索qsort命令,则这些函数必须是等效的。
https://stackoverflow.com/questions/52859845
复制相似问题