iOS开发学习之C语言---C10 函数指针-3
来源:互联网 发布:数据集市的作用 编辑:程序博客网 时间:2024/05/21 09:03
//
// 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来当做函数类型的新名字
typedefBOOL (*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;
}
- iOS开发学习之C语言---C10 函数指针-3
- iOS开发学习之C语言---C10 函数指针-1
- iOS开发学习之C语言---C10 函数指针-2
- iOS开发之c语言基础-函数指针
- iOS开发学习之C语言---C05 函数-3
- ios开发-c语言之C语言函数的学习
- 【学习ios之路:C语言】指针函数
- ios开发-c语言之指针的学习
- iOS开发学习之C语言---C07 指针-1
- iOS开发学习之C语言---C07 指针-2
- iOS开发学习之C语言---C08 高级指针-1
- iOS开发学习之C语言---C08 高级指针-12
- iOS开发之--C语言之指针
- IOS开发系列--C语言之指针
- IOS开发系列--C语言之指针
- iOS开发系列--C语言之指针
- IOS开发系列--C语言之指针
- ios开发之c语言基础-指针
- iOS开发学习之C语言---C10 函数指针-2
- leetcode Problem1 two sum
- 最长公共上升子序列——hdu1423 Greatest Common Increasing Subsequence
- static 剖析(C++)
- JSP/Servlet-----10、JSP2的自定义标签
- iOS开发学习之C语言---C10 函数指针-3
- iOS开发学习之C语言---C11 二维数组、字符串数组、多维数组
- 值得推荐的C/C++框架和库
- leetcode15 3Sum
- 排序算法之Bucket Sort
- 二维数组查询
- samsung s3 gt-19300 开发 键盘回车事件
- 设计模式——行为型模式
- iOS中操作SQLite数据库