函数指针
将一个函数作为另一个函数的参数是函数指针义不容辞的责任
- 传递参数时仅使用函数名为传递地址,若加上参数则调用返回值
- 声明指向函数的指针时,先声明函数,再用(*p)替换函数名即可(一定要加括号,否则为返回指针的函数,而非指向函数的指针)
- 传递函数时也应该将函数的参数列表一并传入
以计时函数为用法示例:
插播一段预备知识——计时函数
利用C++<ctime>计时函数
double duration = ((double)(stop - start)) / CLOCKS_PER_SEC;
利用C<time.h>计时函数
double duration = ((double)(stop - start)) / CLK_TCK;
以冒泡排序为计时函数示例 :
再来一段预备知识——冒泡排序
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
完整示例:
#include <iostream>
#include <ctime>
using namespace std;
double estimate(int n, int a[],void(*p)(int n, int a[]));
void sort(int n, int a[]);
void (*q)(int n, int a[]);
clock_t start, stop;
int c = 0;
int main()
{
q = sort;
int x;
int y[100];
cin >> x;
for (int i = 0; i < x; i++)
{
cin >> y[i];
}
double t=estimate(x, y, q);
cout <<endl<<"Time = " << t<<"ms";
return 0;
}
double estimate(int n, int a[],void(*p)(int n, int a[]))
{
start = clock();
for(c=0;c<1000000;c++)
p(n, a);
stop = clock();
double duration = ((double)(stop - start)) / (1000*CLOCKS_PER_SEC);
return duration;
}
void sort(int n, int a[])
{
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
if (c == 0)
{
for (int i = 0; i < n; i++)
cout << a[i]<<" ";
}
}
解释一下计时函数中看似无意义的循环:计算机跑得太快啦,累积法才能记录下一点点的时间