我举个排序的例子
#include
#include
typedef struct person {
int age;
char name[20];
double height;
} person;
int sortOnAge(person* a, person* b) // 以年龄排序,用于回调
{
return a->age age;
}
int sortOnName(person* a, person* b)// 以姓名排序,用于回调
{
return strcmp(a->name, b->name);
}
int sortOnHeight(person* a, person* b)// 以身高排序,用于回调
{
return a->height height;
}
void sort(person* a, int n, int (*comparator)(person* a, person* b)) // 排序用函数,接受待排数组和比较用回调函数
{
int i, j;
person t;
for(i = 0; i < n; i) {
for(j = 0; j < n-i-1; j) // 简单冒泡排序
if(comparator(a j, a j 1)) { // 调用回调函数比较
memcpy(&t, a j, sizeof(t));
memcpy(a j, a j 1, sizeof(t));
memcpy(a j 1, &t, sizeof(t));
}
}
}
void show(const char* msg, person* p, int n) // 输出数组
{
puts(msg);
int i;
for(i = 0; i < n; i)
printf("%d%s%。
2f
", p[i]。age, p[i]。name, p[i]。height);
putchar('
');
}
int main()
{
person a[] = {
15, "lex", 153。
5,
14, "jack", 155。8,
13, "liu", 144。8,
16, "king", 165。3,
15, "Ben", 159。
7
};
show("origin:", a, 5);
sort(a, 5, sortOnAge); show("sort on age:", a, 5); // 以年龄排序
sort(a, 5, sortOnName); show("sort on name:", a, 5); // 以姓名排序
sort(a, 5, sortOnHeight); show("sort on height:", a, 5); // 以身高排序
}
可能你已经看出来了,对于这个排序函数,如果你不用回调的话,你可以使用以下几种方式来等效
第一:写三个sort函数
缺点:代码冗余,复用性不高
第二:sort函数接受一个数字,用于定义常量判断排序的依据
比如sort(person* a, int n, int cmpmode)
。
。。
switch(cmpmode)
case SORT_ON_AGE: { cmp = a[i]。age < a[i 1]。age }; break;
case SORT_ON_NAME: { cmp = a[i]。
name< a[i 1]。name }; break;
。。。。。
if(cmp){ /*交换*/ }
缺点:这个方法比方法一要好,不过仍不够灵活,而且同样造成代码冗余,缺乏复用性,有n种排序选择就要写n个cmp = a[i]。
xxx < a[i 1]。xxx
到这里你已经看出回调函数的好处了吧。
特别地,使用回调函数可以在一定程度上封装调用函数的逻辑,这在写库和api的时候就很有用了,比如windows的n多api里都用到回调函数,os来调用你提供的一个函数地址,这种情况你无论如何也不可能自己去实现那个调用api吧,所以回调函数作用多多。
全部