回调函数

来源:互联网 发布:网游辅助软件代理 编辑:程序博客网 时间:2024/06/03 16:13

今天学数据结构看到看到一个问题:

给定另一个100阶多项式 这里写图片描述,用不同方法计算并且比较一下运行时间?

思路是用一个计算时间的函数比较不同方法的速度:

void time_cost(传入的函数){    clock_t start, finish;    double time_length;    start = clock();//start存储的是当前的时刻    {//测试代码块        while (times--){            fun(a);        }        cout << result << endl;    }    finish = clock();//finish存储的是结束的时刻    time_length = (double)(finish - start) / CLOCKS_PER_SEC;//根据两个时刻的差,计算出运行的时间    cout << "Time used is " << time_length << " second." << endl;}

这是两个不同方法函数:

//传统方法void fun_one(double x){    double sum=1;    for (int i = 1; i <= max; i++){        sum += (double)pow(x, i) / (double)i;    }    result = sum;}//第二种方法void fun_two(double x){    double sum = 1/(double)max;    for (int i = max; i > 0 ; i--){        sum = 1 / (double)(i-1+(i==1)) + sum*x;    }    result = sum;}

然后就遇到了问题。函数要怎么传到另外一个函数里面去。后来查了好多资料才发现原来这叫“回调函数”。具体语法如下:

void diaplay(int);void callback(void (*)(int),int);int main(){    int a = 10;    callback(display,a);    return 0;}void display(int num){    cout<<num;}void callback(void (*fun)(int),int a){    fun(a);}

然后 ,原来的问题就解决了

    #include<iostream>#include <time.h>const int max = 100;//累加的值const int times = 100000;//执行次数double result;using namespace std;void fun_one(double);void fun_two(double);void time_cost(void (*)(double),double,int);int main(){    time_cost(fun_one, 1.1, times);    time_cost(fun_two, 1.1,times);}//传统方法void fun_one(double x){    double sum=1;    for (int i = 1; i <= max; i++){        sum += (double)pow(x, i) / (double)i;    }    result = sum;}//第二种方法void fun_two(double x){    double sum = 1/(double)max;    for (int i = max; i > 0 ; i--){        sum = 1 / (double)(i-1+(i==1)) + sum*x;    }    result = sum;}void time_cost(void (*fun)(double),double a,int times){    clock_t start, finish;    double time_length;    start = clock();//start存储的是当前的时刻    {//测试代码块        while (times--){            fun(a);        }        cout << result << endl;    }    finish = clock();//finish存储的是结束的时刻    time_length = (double)(finish - start) / CLOCKS_PER_SEC;//根据两个时刻的差,计算出运行的时间    cout << "Time used is " << time_length << " second." << endl;}
0 0