回调函数
回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数,回调函数不是由该函数的实现方直接调用,而是在特定的条件下,由另一方调用。
接下来看一个快速排序函数qsort
void qsort(void *base, size_t num, size_t width, int(*compare)(const void*elem1, const void*elem2));
此函数有四个参数,第一个参数起始位置,第二个参数是元素个数,第三个参数每个元素所占字节数,第四个参数指向函数的指针。
而第四个参数指针调用的函数就是回调函数
看具体应用
1.快速排整形数据
#include<stdio.h>
#include<stdlib.h>
int cmp(const void*e1, const void*e2)
{
return (*(int*)e1 - *(int*)e2);
}
int main()
{
int i = 0;
int arr1[] = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };
int sz = sizeof(arr1) / sizeof(arr1[0]);
qsort(arr1, sz, sizeof(arr1[1]), cmp);
for (i = 0; i < sz; i++)
{
printf("%d\n", arr1[i]);
}
system("pause");
return 0;
}
2。快速排结构体类型数据
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct S
{
char name[10];
int age;
};
int cmp_name(const void*e1, const void*e2)
{
strcmp((*(struct S*)e1).name, (*(struct S*)e2).name);
}
int main()
{
int i = 0;
struct S arr2[3] = { { "zhangsan", 23 }, { "lisi", 24 }, { "wangwu", 27 } };
int sz = sizeof(arr2) / sizeof(arr2[0]);
qsort(arr2, sz, sizeof(arr2[1]), cmp_name);
for (i = 0; i < sz; i++)
{
printf("%s\n", arr2[i].name);
}
system("pause");
return 0;
}
上面代码中用红笔标出的就是回调函数
上面我们了解了qsort函数,接下来我们用冒泡法模拟实现一个qsort称之为My_qsort
void Swap(char*buf1, char*buf2, int k)//交换两个元素
{
int w = 0;
for (w = 0; w < k; w++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void My_qsort(void*base, int num, int width, int(*pf)(const void*e1, const void*e2))
{
int i = 0;
int j = 0;
for (i = 0; i < num - 1; i++)
{
for (j = 0; j < num - 1 - i; j++)
{
if (pf((char*)base + width*(j), (char*)base + width*(j + 1))>0)
{
Swap((char*)base + width*(j), (char*)base + width*(j + 1), width);
}
}
}
}
测试一下
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int cmp(const void* e1, const void* e2)
{
return (*(int*)e1 - *(int*)e2);
}
void Swap(char*buf1, char*buf2, int k)//交换两个元素
{
int w = 0;
for (w = 0; w < k; w++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void My_qsort(void*base, int num, int width, int(*pf)(const void*e1, const void*e2))
{
int i = 0;
int j = 0;
for (i = 0; i < num - 1; i++)
{
for (j = 0; j < num - 1 - i; j++)
{
if (pf((char*)base + width*(j), (char*)base + width*(j + 1))>0)
{
Swap((char*)base + width*(j), (char*)base + width*(j + 1), width);
}
}
}
}
int main()
{
int i = 0;
int arr1[] = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };
int sz = sizeof(arr1) / sizeof(arr1[0]);
My_qsort(arr1, sz, sizeof(arr1[1]), cmp);
for (i = 0; i < sz; i++)
{
printf("%d\n", arr1[i]);
}
system("pause");
return 0;
}
结果是正确的