c++ - 将函数作为参数传递,不知道该函数的参数数量
问题描述
我需要测量一些排序算法的时间。问题是某些函数(算法)可能有 2 个参数(例如冒泡排序)或 3 个参数(快速排序)。我不知道如何准备我的函数以接受两种类型的函数(2 参数和 3 参数)。
我正在考虑为每个只有 2 个参数的函数添加一些默认参数,然后在我的get_time_calculations
声明中这样声明:
double get_time_calculations(void (*f)(int *, int, int), int *tab, int n) {
...
}
但是这个解决方案只是解决方法,也许有更好的方法来做到这一点而不改变准备好的算法的参数?
我测量功能时间执行的功能:
double get_time_calculations(void (*f)(int *, int), int *tab, int n) {
clock_t begin, end;
begin = clock();
f(tab, n);
end = clock();
randomize(tab, n, -100, 201);
return (double)(end - begin)/CLOCKS_PER_SEC;
}
我的功能是测试所有算法:
void test1(int *ran_tab, int n) {
cout << endl << "Insert sort: " << get_time_calculations(insert_sort, ran_tab, n) << "ms" << endl;
cout << endl << "Bubble sort: " << get_time_calculations(bubble_sort, ran_tab, n) << "ms" << endl;
cout << endl << "Selection sort: " << get_time_calculations(selection_sort, ran_tab, n) << "ms" << endl;
cout << endl << "Quick sort: " << get_time_calculations(quick_sort, ran_tab, n) << "ms" << endl;
cout << endl << "Shell sort: " << get_time_calculations(shell_sort, ran_tab, n) << "ms" << endl;
cout<<endl<<"Heap sort: "<<get_time_calculations(heap_sort, ran_tab, n)<<"ms"<<endl;
}
解决方案
推荐阅读
- node.js - 如何在数据库中更新字段时更新 redux 数据(React-Native | NodeJS)
- laravel - 如何在 Laravel 中显示 2 个表中的数据?
- r - 使用 officedown::rdocx_document 时,Rmd 报告不会从参考文档的标题中导入图像:
- c# - Xamarin/C# - 在日期范围内查找周末的方法。为什么我陷入循环并且无法增加当前日期?
- amazon-s3 - 使用 Regex 将日志从 S3 导入 Athena
- swift - 如何在视图中使用 ForEach 将 Swift 5 数组索引偏移到某个数字?
- c# - Asp.Net 网站上的随机 ThreadAbortException
- sql - 我得到一个大写的表名调用一个变量
- node.js - 使用 mongodb lookyp 和 nodejs 获取计数值
- azure - SonarQube Azure AD SAML 身份验证