我正在学习 c++,我想知道是否可以将一个方法作为参数传递给另一个方法?
我想要做的大致轮廓是这样的:
void insertionSort() {
//perform sort
}
int timeOfOperation(methodInQuestion) {
// time 1
methodInQuestion;
//time 2
return time2-time;
}
int main() {
cout << timeOfOperation(insertionSort());
return 0;
}
有没有办法做这样的事情?
编辑:
我很欣赏这些回复。不过我还有一个问题。在我的实际代码中,这一切都发生在一个名为 dataStructure 的类中,我正在其他地方创建它的一个实例并调用这些方法。
dataStructure ds();
ds.timeOperation(ds.insertionSort());
当我尝试实施发布的一些解决方案时,我收到此错误:
IntelliSense: no instance of function template
"dataStructure::timeOperation" matches the argument list argument
types are: (void) object type is: dataStructure
我真的不明白为什么创建实例会影响这一点。谁能解释一下?
==================================================== ===========
编辑2:
我将或多或少地发布这部分的确切代码:
//main.cpp
#include "arrayList.h"
#include "arrayListStructure.h"
#include "Person.h"
using namespace std;
int main() {
arrayList<Person> *al = new arrayList<Person>(length);
arrayListStructure als(al);
//als.fillStructure(data);
als.timeOperation(als.insertionSort());
return 0;
}
//arrayListStructure.cpp
#include "arrayListStructure.h"
#include <functional>
double arrayListStructure::timeOperation(std::function<void()> operation) {...}
void arrayListStructure::insertionSort() {...}
arrayListStructure::arrayListStructure(arrayList<Person> *al)
{
this -> al = al;
}
还有更多,但我认为这就是与问题有关的全部