这个问题中的很多可能在现实世界中使用是不切实际的,但我把它作为一个学习过程来做。
我已经开始了一个项目,记录每种类型的排序算法及其效率。我一直在用c++编写每个排序算法作为模板函数,如下所示:
template <class T>
void bubble_sort(T arr[], int numItems) {
for (int i = 0; i < numItems; i++) {
for (int j = 0; j < numItems - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}我希望我的驱动程序在几组数据上测试每个算法的效率,并希望通过创建一个测试每个排序算法的模板函数来进一步推广我的过程,但我不知道如何做到这一点。以下是我的想法,但它不起作用:
template<typename F, typename T>
double test(F arr[], int numItems, T func) {
clock_t start, finish;
start = clock();
T(arr, numItems);
finish = clock();
return (double)(finish - start) / CLOCKS_PER_SEC;
}测试的内容并不重要,但我希望能够像这样传入排序函数:
double duration = test<int>(arr, numItems, bubble_sort<int>);任何帮助构建这个函数的人都会更好;
发布于 2017-09-28 09:04:49
我想您必须在test()中调用func(),如下所示
func(arr, numItems);而不是
T(arr, numItems);https://stackoverflow.com/questions/46459176
复制相似问题