根据从控制台输入的信息(name,age,或score),来给5个学生排序

#import <Foundation/Foundation.h>
//定义学生体
typedef struct student{
    char name[20];
    int age;
    float score;
}stu;
typedef BOOL (*pStu)(stu ,stu);
//建立字符串和函数之间一一对应关系
typedef struct nameFunctionPair {
    char name[20];//存储函数对应的字符串
    pStu  function ;//存储字符串对应的函数的地址
}NameFunctionPair;

BOOL sortStudentName(stu st1,stu st2)
{
    return strcmp(st1.name, st2.name) >0;//比较name的大小
}
BOOL sortStudentAge(stu st1,stu st2)
{
    return st1.age > st2.age;
}
BOOL sortStudentScore(stu st1,stu st2)
{
    return st1.score > st2.score;
}
pStu getFounction(char *name  ,NameFunctionPair *pair ,int number)
{  //根据输入的内容,查找符合的条件
    for (int i = 0 ; i <number; i++) {
        if (strcmp(name, (pair + i)->name) ==0) {
            return (pair +i)->function;
        }
    }
    return NULL;
}
//排序函数
void sortStudent(stu *p,int count,char *name,NameFunctionPair *pair,int number)
{
    pStu function =getFounction(name, pair, number);
    for (int i = 0 ; i < count - 1; i++) {
        for (int j = 0; j < count - 1 - i; j++) {
            if (function(*( p + j ),*(p +j +1))){
                stu  temp = *(p + j );
                *(p + j ) = *(p +j + 1);
                *(p +j +1) = temp;
            }
        }
    }
}
//输出学生信息
void printStudent(stu *p,int count)
{
    for (int i = 0; i < count; i ++) {
        printf("name: %s  age:  %d  score:  %.2f\n",(p + i )->name,(p + i)->age,(p +i )->score);
    }
}

int main(int argc, const char * argv[])
{
    stu st[5] = {
        {"xiao",21,56},
        {"zhang",4,38},
        {"wang",12,89},
        {"zhao",9,40},
        {"tang",54,90},
    };
    //创建一个匹配表
    NameFunctionPair pair[3] ={
        {"name",sortStudentName},
        {"age",sortStudentAge},
        {"score",sortStudentScore}
    };
    char tempName[20] = {0};//用来接受从控制台输入的字符串
    printf("请输入排序的方式(name或age或score):");
    scanf("%s",tempName);
    //对学生排序
    sortStudent(st, 5, tempName, pair, 3);
    printStudent(st, 5);
       return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值