【发布时间】:2023-03-12 12:17:01
【问题描述】:
我有一个关于将比较函数传递给sort() 的问题。
我想要做的是定义一个sort() 函数,该函数在计算时考虑到我要在其中进行排序的类的成员变量。
基本上,我的代码如下所示(简化为仅显示相关部分):
MappingTechnique.h
struct MappingTechnique {
vector<int> usedIndexCount;
};
struct SimpleGreedyMappingTechnique : MappingTechnique {
bool sortByWeights(int index1, int index2);
};
MappingTechnique.m
bool SimpleGreedyMappingTechnique::sortByWeights(int index1, int index2) {
return usedIndexCount[index1] > usedIndexCount[index2];
}
void SimpleGreedyMappingTechnique::processFrame(Frame frame) {
vector<int> payloadIndices = <generate the vector>
// sort the payload indices according to their current usedIndexCount
sort(payloadIndices.begin(), payloadIndices.end(), sortByWeights);
}
此代码无法编译,它给出以下错误:
error: reference to non-static member function must be called
并指向sortByWeights。
甚至可以使用类的成员函数进行排序吗?如果是,我该如何实现?
【问题讨论】: