#import <Foundation/Foundation.h> typedef struct { char name[20]; int age; float score; }Stu; //建立字符串和函数之间的一一对应关系. typedef BOOL (*PStu) (Stu stu1,Stu stu2) ; typedef struct nameFunctionPair{ char name[20]; //存储函数对应的字符串 PStu function; //存储字符串对应函数的地址 }NameFunctionPair; //按年龄排序 BOOL sortStudentByAge(Stu stu1,Stu stu2 ) { return stu1.age > stu2.age; } //成绩 BOOL sortStudentByScore(Stu stu1,Stu stu2 ) { return stu1.score > stu2.score; } //姓名 BOOL sortStudentByName(Stu stu1,Stu stu2 ) { return strcmp(stu1.name, stu2.name) >0; } PStu getFunctionByName (char *name , NameFunctionPair *p , int count ) { int i = 0; for (i = 0 ; i < count; i ++) { if (strcmp(name, (p + i)->name) == 0) { //如果匹配到对应的函数,将函数地址返回 return (p + i)->function; } } return NULL; //如果没有匹配到对应的函数,就返回NULL; } //三个函数之间唯一的不同就在于,冒泡排序中判断条件不同. void sortStudent(Stu *p , int count , char *name, NameFunctionPair *pair, int number) { PStu funtion = getFunctionByName(name, pair, number); for (int i = 0 ; i < count -1; i ++) { for (int j= 0 ; j < count -1-i; j ++) { if (funtion(*(p + j),*(p + j + 1))) { Stu temp = *(p + j); *(p + j) = *(p + j + 1); *(p + j + 1) = temp; } } } } void outPut(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); } } //根据给定的字符串查找匹配表,找出对应的函数. //name 用来接受匹配的字符串 //p 用来接受匹配表 //count 接受匹配表元素的个数 int main(int argc, const char * argv[]) { Stu stu[5] = { {"zhang",20,80}, {"wang", 22,82}, {"li",23,86}, {"zhao",22,83}, {"liu",20,89} }; Stu *p = NULL; p = stu; //创建匹配表 NameFunctionPair name[3] = { {"name",sortStudentByName}, {"score" , sortStudentByScore}, {"age" , sortStudentByAge} }; char tempName[20] = {0}; printf("请输入排序的方式(姓名:name , 年龄: age , 成绩: score)\n"); scanf("%s",tempName); //对学生排序 sortStudent(p, 5, tempName, name, 3); outPut(p, 5); return 0; }
代码案例(结构体,函数指针,指针函数,冒泡排序) 修改,布布扣,bubuko.com
原文地址:http://qccccc.blog.51cto.com/6004423/1532985