std::sort
需要一个比较器,可以简单地称为compare(a,b)
。 (指向成员函数的指针)不合适,因为它需要调用一个对象,因此您需要一个包装器将成员函数绑定到一个对象,并使其可以仅通过要比较的两个值来调用。
在 C++11 中,您可以将成员函数绑定到对象:
sort(mCurrentGeneration.begin(),mCurrentGeneration.end(),
std::bind(&GenericGeneticSolver::solutionComparer, this,
std::placeholders::_1, std::placeholders::_2));
或者你可以使用 lambda:
sort(mCurrentGeneration.begin(),mCurrentGeneration.end(),
[this](T first,T second) { return solutionComparer(first, second); });
从历史上看,您必须创建自己的函子,也许是这样的:
struct SolutionComparer {
IGenticSolverHelper<T>* helper;
SolutionComparer(IGenticSolverHelper<T>& helper) : helper(&helper) {}
bool operator()(T first,T second) {
return helper->Cost(first) < helper->Cost(second);
}
};
sort(mCurrentGeneration.begin(),mCurrentGeneration.end(),
SolutionComparer(mSolverHelper));