【发布时间】:2021-04-23 08:34:22
【问题描述】:
我正在编写一系列排序算法并计算每个算法的执行时间。
#include <iostream>
#include <vector>
#include <chrono>
#include <utility>
#include "sort.h"
template<class T>
void timeTaken(void (*f)(std::vector<T>& nums))
{
auto t1 = std::chrono::high_resolution_clock::now();
f();
auto t2 = std::chrono::high_resolution_clock::now();
double duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << duration << " microseconds";
// return duration;
}
template<typename T>
void display(std::vector<T>& nums)
{
for(int x : nums) std::cout << x << " ";
std::cout << "\n\t ---------------------------------- \n";
}
void displayTesting()
{
std::cout << "testing .... \n";
}
int main()
{
std::vector<int> A {4,5,2,7,1,10,15};
std::cout << "ORIGNAL ARRAY: ";
display(A);
bubbleSort(A);
timeTaken(&display); //ERROR: No matching function for call "time Taken"
std::cout << "BUBBLE SORT: ";
display(A);
std::cout << "\n";
return 0;
}
当我尝试将 displayTesting() 作为 timeTaken() 的参数时,它工作正常(当然我在 (*f) 之后删除了参数)。所以我认为问题基本上是我如何将某个函数的参数带入 timeTaken() 函数。
【问题讨论】:
标签: c++ function templates parameters