-
理解回调函数的使用
回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给
另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
举例:
- 使用qsort函数排序各种类型的数据
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
struct Stu
{
char name[20];
int age;
};
int cmp_int(const void* e1, const void* e2)//整形的比较
{
return (*(int*)e1 - *(int*)e2);
}
int cmp_stu_by_age(const void* e1, const void* e2)
{
return ((struct Stu*)e1)->age-((struct Stu*)e2)->age;
}
int cmp_stu_by_name(const void* e1, const void* e2)
{
return strcmp(((struct Stu*)e1)->name,((struct Stu*)e2)->name);
}
int main()
{
//int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
//int sz = sizeof(arr) / sizeof(arr[0]);
struct Stu arr[] = {{ "zhangsan",20}, { "lisi",15},{"wangwu" ,12}};
int sz = sizeof(arr) / sizeof(arr[0]);
//qsort(arr, sz, sizeof(arr[0]), cmp_int);
//qsort(arr, sz, sizeof(arr[0]), cmp_stu_by_age);
qsort(arr, sz, sizeof(arr[0]), cmp_stu_by_name);//qsort(起始位置, 元素个数,元素大小,比较函数)
/*for (int i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}*/
system("pause");
return 0;
}
- 模仿qsort的功能实现一个通用的冒泡排序
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <assert.h>
struct Stu
{
char name[20];
int age;
};
int cmp_int(const void* e1, const void* e2)//整形的比较
{
return (*(int*)e1 - *(int*)e2);
}
int cmp_stu_by_age(const void* e1, const void* e2)
{
return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}
int cmp_stu_by_name(const void* e1, const void* e2)
{
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}
void _Swap(char* buf1,char* buf2,size_t width)
{
assert(buf1&&buf2);
unsigned int i = 0;
for (i = 0; i < width; i++)//按字节交换
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void bubble_sort(void* base, int num, int width,
int(*cmp)(const void* e1, const void* e2))
{
assert(base&&cmp);
int i = 0;
int j = 0;
for (i = 0; i < num - 1; i++)
{
for (j = 0; j < num - 1 - i; j++)
{
if (cmp((char*)base + j*width, (char*)base + (j + 1)*width)>0)
{
//交换
_Swap((char*)base + j*width, (char*)base + (j + 1)*width,width);
}
}
}
}
int main()
{
/*int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz, sizeof(arr[0]), cmp_int); *///qsort(起始位置, 元素个数,元素大小,比较函数)
struct Stu arr[] = { { "zhangsan", 20 }, { "lisi", 15 }, { "wangwu", 12 } };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz, sizeof(arr[0]), cmp_stu_by_name);
for (int i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
system("pause");
return 0;
}