十七、函数指针高级(动态排序)
1.学生结构体数组,按成绩排序、按年龄排序,按名字大小排序
示例:
typedef struct stu{//定义一个结构体变量
char name[40];
int age;
float score;
}Student;
void printfStudents(Student *s , int count);
void printfStudents(Student *s , int count){//打印结构体数组
printf(“========================\n”);
for(int i = 0 ; i < count ; i ++){
printf(“%s %d %f\n”,s[i].name,s[i].age,s[i].score);
}
printf(“=========================\n”);
}
typedef BOOL(*SORT)(Student s1 , Student s2);//用typedef定义一个布尔值的函数指针
BOOL sortUseAge(Student s1 , Student s2);
BOOL sortUseAge(Student s1 , Student s2){//布尔值类型的函数,年龄
return s1.age > s2.age;
}
BOOL sortUseScore(Student s1 , Student s2);
BOOL sortUseScore(Student s1 , Student s2){//布尔值类型的函数,分数
return s1.Score > s2.Score;
}
BOOL sortUseName(Student s1 , Student s2);
BOOL sortUseName(Student s1 , Student s2){//布尔值类型的函数,名字
return strcpy(s1.name , s2.name) > 0?YES : NO;
}
//旧方法对比
//void sort(Student *s , int count);
//void sort(Student *s , int count){
// for(int i = 0 ; i < count - 1 ; i ++){
// for(int j = 0 ; j < count - 1 - i ; j ++){
// if(s[j].age > s[j+1].age){
// Student temp = s[j];
// s[j] = s[j+1];
// s[j+1] = temp;
// }
// }
// }
//}
void sort(Student *s , int count , SORT st);//回调函数
void sort(Student *s , int count , SORT st){
for(int i = 0 ; i < count - 1 ; i ++){
for(int j = 0 ; j < count - 1 - i ; j ++){
if(st(s[j] , s[j+1])){
Student temp = s[j];//此处应该借鉴
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
}
int main(){
Student stuff[] = {
{“zhangsan”,23,89},
{“lisi”,25,72},
{“wangle”,18,93},
{“zhaoda”,20,65}
}
printfStudents(stus, sizeof(stus) / sizeof(stuff[0]) );//打印结构体数组
sort(stus, sizeof(stus) / sizeof(stuff[0]) , sortUseAge);//按年龄排序
printfStudents(stus, sizeof(stus) / sizeof(stuff[0]) );//打印结构体数组
sort(stus, sizeof(stus) / sizeof(stuff[0]) , sortUseScore);//按分数排序
printfStudents(stus, sizeof(stus) / sizeof(stuff[0]) );//打印结构体数组
sort(stus, sizeof(stus) / sizeof(stuff[0]) , sortUseName);//按名字排序
printfStudents(stus, sizeof(stus) / sizeof(stuff[0]) );//打印结构体数组
}
坐得住,敲得多,自然就明了