回调函数,qsort函数,与qsort函数的模拟
回调函数:
回调函数就是一个通过函数指针调用的函数,如果你把函数的指针作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这个函数为回调函数,
回调函数不是由该函数的实现方法直接调用,而是在特定的事件或者条件时由另外的一方调用,用于对该事件或者条件响应。
简单的说,就是一个函数的参数里面有一个函数指针参数,而这个函数指针对应的函数要自己用函数实现。很通俗,具体用途,我们来通过qsort函数来看看
void qsort( void *base, size_t num, size_t width, int (__cdecl *compare )(const void *elem1, const void *elem2 ) );
qsort函数原型和参数。int (__cdecl *compare )(const void *elem1, const void *elem2 ) 这个就是函数指针做qsort函数是的参数
那么我们来模拟实现一下qsort函数,用冒泡法。
//实现qsort函数,用冒泡法; #include<stdio.h> #include<stdlib.h> int int_cmp(const void *p1,const void *p2)//回掉函数,这一部分需要自己去实现 { return (strcmp(*(int *)p1,*(int *)p2));//处理字符串 //return (*(int *)p1 > *(int *)p2);//处理整数 } void swap(void *p1,void *p2,int size) { int i = 0; for(i = 0; i<size; i++) { char tmp = *((char *)p1+i); *((char *)p1+i)=*((char *)p2+i); *((char *)p2+i)=tmp; } } void bubble(void *base,int count,int size,int(*cmp)(void *,void *))//用冒泡来实现qsort排序 { int i = 0; int j = 0; for(i=0;i<count-1;i++) { for(j=0;j<count-i-1;j++) { if(cmp((char *)base + j*size,(char *)base + (j+1)*size)>0) { swap((char *)base+j*size,(char *)base+(j+1)*size,size); } } } } int main() { //int arr[] = {5,4,3,2,1,8,6,4}; char *arr[] = {"aaa","ddd","ccc","bbb"}; int i = 0; qsort(arr,sizeof(arr)/sizeof(arr[0]),sizeof(int),int_cmp); for(i=0; i<sizeof(arr)/sizeof(arr[0]);i++) { printf("%s",arr[i]); } printf(" "); return 0; }
实现起来很简单,就是回调函数概念不太好理解。
The qsort function implements a quick-sort algorithm to sort an array of num elements, each of width bytes. The argument base is a pointer to the base of the array to be sorted. qsort overwrites this array with the sorted elements. The argument compare is a pointer to a user-supplied routine that compares two array elements and returns a value specifying their relationship. qsort calls the compare routine one or more times during the sort, passing pointers to two array elements on each call:
这是qsort函数的用法。对任意类型进行排序。