博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
函数指针的用法
阅读量:6536 次
发布时间:2019-06-24

本文共 2339 字,大约阅读时间需要 7 分钟。

按结构体字段进行排序

#include
#include
int compare(void *, void *, int (*)(void *, void *));int orderById(void *, void *);int orderByName(void *, void *);int orderByAge(void *, void *);struct Student { int id; char name[64]; int age; char address[1024];};void arrSort(struct Student *, int, int (*)(void *, void *));int main(void){ struct Student arr[5] = {
{ 20140101, "zhangsan", 24, "china.guangzhou" }, { 20140103, "lisi", 28, "USA.ny" }, { 20140102, "wangwu", 18, "UK" }, { 20140110, "zhaoliu", 19, "china.peking" }, { 20140131, "fwy", 27, "china.nc" }}; printf("\n-----------id升序-----------------\n"); arrSort(arr, 5, orderById); printf("\n-----------name升序-----------------\n"); arrSort(arr, 5, orderByName); printf("\n-----------age升序-----------------\n"); arrSort(arr, 5, orderByAge);}//统一比较函数int compare(void * stu, void * stu2, int (*pt)(void *, void *)){ return (*pt)(stu, stu2);}//按Id升序排列int orderById(void * stu, void * stu2){ struct Student s = *((struct Student *)stu); struct Student s2 = *((struct Student *)stu2); return s2.id - s.id;}//按name升序排列int orderByName(void * stu, void * stu2){ struct Student s = *((struct Student *)stu); struct Student s2 = *((struct Student *)stu2); return strcmp(s2.name, s.name);}//按age升序排列int orderByAge(void * stu, void * stu2){ struct Student s = *((struct Student *)stu); struct Student s2 = *((struct Student *)stu2); return s2.age - s.age;}//结构体数组排序void arrSort(struct Student * arr, int size, int (*pt)(void *, void *)){ int i,j; struct Student temp; for(i = 0; i < size -1; i++) { for(j = 0; j < size - 1 - i; j++) { if(compare(&arr[j], &arr[j + 1], pt) < 0) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } for(i = 0; i < size; i++) { printf("%10d %10s %3d %15s\n", arr[i].id, arr[i].name, arr[i].age, arr[i].address); }}

 

转载于:https://www.cnblogs.com/itpoorman/p/3875472.html

你可能感兴趣的文章