#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;
}