首页 > 解决方案 > 将函数作为参数传递,不知道该函数的参数数量

问题描述

我需要测量一些排序算法的时间。问题是某些函数(算法)可能有 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;
}

标签: c++algorithm

解决方案


推荐阅读