天天看点

iOS开发学习之C语言---C10 函数指针-2

//

//  main.m

//  C10 函数指针-2

//

//  Created by 康亮亮 on 15/10/20.

//  Copyright (c) 2015年 Darling.com. All rights reserved.

//

#import <Foundation/Foundation.h>

#pragma mark typede函数指针

typedef struct student{

    char name[20];

    int age;

    float score;

}Student;

// 使用typedef给函数类型重定义

// 使用PFUNC来当做函数类型的新名字

typedef BOOL (*PFUNC)(Student, Student);

// 按照成绩升序

BOOL sortByScore(Student stu1, Student stu2){

    if (stu1.score > stu2.score) {

        return  YES;

    }else

        return NO;

}

// 按照姓名

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;

}

// 定义一个中间函数,通过这个函数的指针参数,调用不同的排序规则函数

void sortArray(Student student[], int count, PFUNC p ){

    for (int i = 0; i < count - 1; i++) {

        for (int j = 0; j < count - 1 - i; j++) {

            if(p(student[j], student[j + 1])){

                Student temp = student[j];

                student[j] = student[j + 1];

                student[j + 1] = temp;

            }

        }

    }

}

// 封装打印函数

void printStudent(Student *stu, int count){

    for (int i = 0; i < count; i++) {

        printf("%s  %d %.2f\n", stu[i].name, stu[i].age, stu[i].score);

    }

}

int main(int argc, const char * argv[]) {

    // 一个学生结构体数组, 按照姓名给学生升序排列

    Student students[5] = {

        {"zhangsan", 20, 65},

        {"lisi", 19, 75},

        {"wuliu", 23, 85},

        {"jenny", 32, 90},

        {"danny", 25, 96},

    };

    // 根据用户输入的字符判断指针应该指向那个函数

    char string[20];

    printf("请输入要求:\n");

    scanf("%s", string);

    PFUNC p = NULL;

    if (strcmp(string, "sortByName") == 0) {

        p = sortByName;

    }else if(strcmp(string, "sortByAge") == 0){

        p = sortByAge;

    }else if(strcmp(string, "sortByScore") == 0){

        p = sortByScore;

    }

    if(p != NULL){

        sortArray(students, 5, p);

        printStudent(students, 5);

    }

    return 0;

}

继续阅读