天天看點

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;

}

繼續閱讀