回调函数

本文深入探讨了C++回调函数的应用及快速排序算法的优化实践,通过实例展示了如何使用回调函数增强代码的灵活性和复用性,并详细解析了经典快速排序算法的实现过程。
//头文件


#pragma once           //包含pragma once语句的文件只会被编译一次  
//表示在编译的时候, 这个文件只被包含(include)一次
//这样, 可以减少整个编译过程中打开这个文件的次数


#include <stdio.h>
#include <tchar.h>
#include <stdlib.h>


//函数1


typedef void (*FP)(unsigned int a, unsigned int b);


void PointerReceive(unsigned int a, unsigned int b)
{
 a = (a > b) ? a : b;
 printf("THE BIG ONE IS  = %d", a);
}


void DataDeal(FP PCB)
{
 unsigned int m, n;
 m  =  5;
 n  =  8;
 PCB(m, n);
}


int _tmain(void)
{
 DataDeal(PointerReceive);


 system("pause");
}


//函数2


typedef void (*callback_t)(void *);


void repeat_three_times(callback_t f, void *para)
{
 f(para); 
 f(para); 
 f(para);
}
//调用者则提供回调函数,然后调用repeat_three_times来实现:
void say_hello(void *str) /* 回调函数1 */
{
 printf("Hello %s\n", (const char *)str);
}


void count_numbers(void *num) /* 回调函数2 */
{
 int i;


 for(i = 1; i <= (int)num; i++) 
  printf("%d ", i); 
 putchar('\n');
}


int main(void)
{
 repeat_three_times(say_hello, (void *)"Guys"); 
 repeat_three_times(count_numbers, (void *)4);


 system("pause");


 return 0;
}


 


//经典的快排


typedef void(*pcb)(char *);


void fCallback(char *s)
{
 printf("Hello ~!\n");
}


void GetCallBack(pcb callback)
{
 printf("begin ~!\n");
}


int list[5] = {54, 21, 11, 67, 22};


int sort_function(const void *a,const void *b)
{
 return *(int *)a - *(int *)b;
}


int _tmain(int argc, _TCHAR* argv[])
{


 /*fCallback(NULL);
 GetCallBack(fCallback);*/


 int x;


 qsort((void *)list, 5, sizeof(list[0]), sort_function);


 for (x = 0; x < 5; x ++)
 {
  printf("%i\n",list[x]);
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值