gpt4 book ai didi

c - bsearch() 按名称比较

转载 作者:行者123 更新时间:2023-12-01 13:50:12 24 4
gpt4 key购买 nike

我有一个struct employee比较器和main:

#define MAX_SIZE 20
typedef struct Employee{
char name[MAX_SIZE];
int salary;
int experience;
} employee_t;

void main()
{
int i;

employee_t** employeeArray = (employee_t**)malloc(sizeof(employee_t*)*5);
employee_t nonExstingEmployee = {"v"};

for(i=0 ; i < 2 ; i++)
{
employeeArray[i] = (employee_t*)malloc(sizeof(employee_t)); //alocate each employee
readEmployee( employeeArray[i] );
}

puts("beforesort\n");

for(i=0; i <2 ; i++)
{
printEmployee(employeeArray[i]);
}

puts("after salary sort\n");
qsort(employeeArray, 2, sizeof(employee_t*), compareEmployeesBySalary);
for(i=0; i < 2 ; i++)
printEmployee( employeeArray[i] );

if (bsearch(&nonExstingEmployee, employeeArray, MAX_SIZE, sizeof(employee_t), compareEmployeesByName) == 0)
puts("employee found");
else
puts("no employee found");

}


int compareEmployeesBySalary(const void* a, const void* b){
employee_t* one = *(employee_t **)a;
employee_t* two = *(employee_t **)b;

if (one->salary == two->salary)
return 0;
else if (one->salary > two->salary)
return 1;
else
return -1;
}

int compareEmployeesByName(const void* a,const void* b)
{
employee_t* one = *(employee_t**)a;
employee_t* two = *(employee_t**)b;

if(strcmp(&one->name, &two->name) == 0)
{
return 1;
}

return 0;
}

我需要使用 bsearch 比较姓名(与数组中不存在的一些员工),我的 qsort 函数有效(按薪水比较)无论我如何为 bsearch 初始化员工,它总是说它不存在(我试图先与现有员工一起测试),

我应该如何初始化我的员工(或者我应该改变什么?)


[根据评论更新:]

这是我的 readEmployee():

void readEmployee(employee_t *emp)
{
fflush(stdin);
printf("Please enter Employee's name:(max 19 chars)");
scanf("%s", emp->name);

fflush(stdin);
printf("Please enter Employee's salary:");
scanf("%d", &(emp->salary));

fflush(stdin);
printf("Please enter Employee's experience:");
scanf("%d", &(emp->experience));
}

我正在比较 nonExstingEmployee(存在于数组中用于测试)和我的 employeeArray

最佳答案

问题很简单:您按薪水qsort 而按姓名bsearch。这是行不通的。

bsearch排序数组 中执行二进制搜索。不是任何排序的数组,而是根据搜索条件排序的数组。您必须事先按名称执行 qsort 或坚持使用 lsearch(即不依赖于先前排序的线性搜索)。

关于c - bsearch() 按名称比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32422205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com