#import <Foundation/Foundation.h>
//定义一个结构体,使用函数回调实现动态排序(年龄.姓名.分数)
typedef struct student{
char name[50];
int age;
float score;
}Student;
BOOL compareName(Student stu1,Student stu2); //声明
BOOL compareName(Student stu1,Student stu2){ //按姓名排序实现
return strcmp(stu1.name, stu2.name);
}
BOOL compareAge(Student stu1,Student stu2); //声明
BOOL compareAge(Student stu1,Student stu2){ //按年龄排序实现
return stu1.age>stu2.age?YES:NO;
}
BOOL compareScore(Student stu1,Student stu2); //声明
BOOL compareScore(Student stu1,Student stu2){ //按分数排序实现
return stu1.score>stu2.score?YES:NO;
}
void bubbleArray(Student *a,int count,BOOL (*p)(Student,Student));
void bubbleArray(Student *a,int count,BOOL (*p)(Student,Student)){ //运行时函数,参数:一个指针变量,一个长度,一个函数指针
for (int i=0; i<count-1; i++) {
for (int j=0; j<count-1-i; j++) {
if (p(a[ j ],a[j+1])) { //由参数函数指针所指向的函数决定按什么类型排序
Student temp=a [ j ];
a[ j ]=a[j+1];
a[j+1]=temp;
}
}
}
for (int i=0; i<count; i++) { //遍历
printf("%s %d %.2f \n",a[ i ].name,a[ i ].age,a[ i ].score);
}
}
int main(int argc, const char * argv[]) {
Student stuArray[ 5 ]={ //定义一个结构体数组
{"***",98,80.0},
{"aobama",75,60.1},
{"benladeng",55,56.3},
{"pujing",58,88.6},
{"chengguan",63,98.0}
};
BOOL (*p)(Student,Student)=NULL; //函数指针初始化
p=compareAge; //为函数指针赋值,指向的是函数compareAge的地址
// p=compareName;
// p=compareScore;
bubbleArray(stuArray, 5, p); //调用函数
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探