//
// main.m
// C10 函数指针-3
//
// Created by 康亮亮 on 15/10/20.
// Copyright © 2015年 quanzheng.com. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef struct student{
char name[20];
int age;
float score;
}Student;
// 使用typedef给函数类型重命名
// 使用PFUNC来当做函数类型的新名字
typedef BOOL (*PFUNC)(Student, Student);
typedef struct FuncList{
char funcString[20];
PFUNC p;
}FuncList;
// 封装一个打印函数
void printStudents(Student *students, int count){
for (int i = 0; i < count; i++) {
printf("name = %s, age = %d, score = %.2f\n", students[i].name, students[i].age, students[i].score);
}
}
// 定义一个函数,实现按照姓名升序排列
BOOL sortByName(Student stu1, Student stu2)
{
if (strcmp(stu1.name, stu2.name) > 0) {
return YES;
} else
return NO;
}
// 按照年龄升序排列
BOOL sortByAge(Student stu1, Student stu2){
if (stu1.age > stu2.age) {
return YES;
} else
return NO;
}
// 按照成绩升序
BOOL sortByScore(Student stu1, Student stu2){
if (stu1.score > stu2.score) {
return YES;
} else
return NO;
}
// 定义一个中间函数,通过这个函数的指针参数,调用不同的排序规则函数
void sortArray(Student student[], int count, PFUNC p){
// p(student, count);
for (int i = 0; i < count-1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if ( p(student[j], student[j+1]) ) {
Student temp = student[j];
student[j] = student[j+1];
student[j+1] = temp;
}
}
}
}
PFUNC returnFunction(char funcString[], FuncList funcArray[], int count){
for (int i = 0; i < count; i++) {
if ( strcmp(funcArray[i].funcString, funcString) == 0){
return funcArray[i].p;
}
}
return NULL;
}
int main(int argc, const char * argv[]) {
// 一个学生结构体数组,按照姓名给学生升序排列
// 制造数据
Student students[] = {
{"aZhiNan", 18, 90},
{"bXianCheng", 19, 99},
{"eLuoLuo", 2, 22},
{"dLiangLiang", 23, 100}
};
// 创建函数列表数据
FuncList funcArray[] = {
{"sortByAge",sortByAge},
{"sortByName", sortByName},
{"sortByScore", sortByScore}
};
// 根据用户输入的字符判断指针应该指向那个函数
char string[20];
scanf("%s", string);
PFUNC p = NULL;
p = returnFunction(string, funcArray, 3);
if (p != NULL) {
sortArray(students, 4, p);
printStudents(students, 4);
}
return 0;
}