您需要实现一个排序功能,根据需要比较结构
int compare(const void *s1, const void *s2)
{
struct employee *e1 = (struct employee *)s1;
struct employee *e2 = (struct employee *)s2;
int gendercompare = strcmp(e1->gender, e2->gender);
if (gendercompare == 0) /* same gender so sort by id */
return e1->id - e2->id;
else
return -gendercompare; /* the minus puts "male" first as in the question */
}
然后使用标准库中的 qsort 。
qsort(data, count, sizeof(struct employee), compare);
在 compare 函数中,您可能想要检查 id 是否相等,然后您可以按名称排序(也可以使用strcmp()
)但是您喜欢。
编辑:刚刚编译并修复了这个。这是一个小测试程序
#include <stdio.h>
#include <stdlib.h>
struct employee{
char gender[13];
char name[13];
int id;
};
int compare(const void *s1, const void *s2)
{
struct employee *e1 = (struct employee *)s1;
struct employee *e2 = (struct employee *)s2;
int gendercompare = strcmp(e1->gender, e2->gender);
if (gendercompare == 0) /* same gender so sort by id */
return e1->id - e2->id;
else
return -gendercompare;
}
main()
{
int i;
struct employee info[]={{"male","Matt",1234},{"female","Jessica",2345},{"male","Josh",1235}};
for (i = 0; i < 3; ++i)
printf("%d\t%s\t%s\n", info[i].id, info[i].gender, info[i].name);
qsort(info, 3, sizeof(struct employee), compare);
for (i = 0; i < 3; ++i)
printf("%d\t%s\t%s\n", info[i].id, info[i].gender, info[i].name);
}
带输出:
$ ./a.exe
1234 male Matt
2345 female Jessica
1235 male Josh
1234 male Matt
1235 male Josh
2345 female Jessica