代码积累:结构体排序

因为结构体类型包含了很多成员类型,故排序的时候需要根据成员进行排序
下面进行一个小项目:
一共四个同学,每个同学有不同的名字、id和类别
名字分别是:Lily、Make、Anna、Jack
id分别是:2、4、1、3
类别分别是:‘A',’C‘,’B',‘B'
要求输入1时,返回按名字排序完成的列表
输入2时,返回按id排序完成的列表
输入3时,返回按类别排序完成的列表

完整代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stu { //结构体类型定义
    char name[20];
    int id;
    char type;
};
void print_struct(struct stu s[]) { //打印结构体
    printf("姓名  id   类别\n");
    for (int i = 0; i < 4; i++)
        printf("%4s  %2d    %1c\n", s[i].name, s[i].id, s[i].type);
}
//对name排序
int cmp_by_name(const void* e1, const void* e2) {
    return strcmp(((struct stu*)e1)->name, ((struct stu*)e2)->name);
}
//对id排序
int cmp_by_id(const void* e1, const void* e2) {
    return ((struct stu*)e1)->id - ((struct stu*)e2)->id;
}
//对type排序
int cmp_by_type(const void* e1, const void* e2) {
    return ((struct stu*)e1)->type - ((struct stu*)e2)->type;
}
int main() {
    int x;
    //函数指针数组 -- pfun
    int (*pfun[5])(const void*, const void*) = { NULL, cmp_by_name, cmp_by_id, cmp_by_type };
    struct stu s[4] = { {"Lily", 2, 'A'}, {"Make", 4, 'C'}, {"Anna", 1, 'B'}, {"Jack", 3, 'B'} };
    int sz = sizeof(s) / sizeof(s[0]);
    printf("请输入(1为按name排序,2为按id排序,3为按type排序)\n");
    scanf("%d", &x);
    qsort(s, sz, sizeof(s[0]), pfun[x]);
    print_struct(s);
}










全部评论

相关推荐

04-14 20:10
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务