nbu*_*urk 3 c++ sorting functor
我有一个关于将比较函数传递给的问题sort().
我想要做的是定义一个sort()函数,该函数在计算时考虑了我想要进行排序的类的成员变量.
基本上,我的代码看起来像这样(简化为只显示相关部分):
MappingTechnique.h
struct MappingTechnique {
vector<int> usedIndexCount;
};
struct SimpleGreedyMappingTechnique : MappingTechnique {
bool sortByWeights(int index1, int index2);
};
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
此代码无法编译,它会出现以下错误:
error: reference to non-static member function must be called
Run Code Online (Sandbox Code Playgroud)
并指出sortByWeights.
甚至可以使用类的成员函数进行排序吗?如果是,我该如何实现呢?
它是,但一般来说,我鼓励只使用适当的函子或lambda:
std::sort(payloadIndices.begin(), payloadIndices.end(), [this](int a, int b){
return this->sortByWeights(a, b);
});
Run Code Online (Sandbox Code Playgroud)
std::mem_fn:auto sorter = std::bind(std::mem_fn(SimpleGreedyMappingTechnique::sortByWeights), this);
std::sort(payloadIndices.begin(), payloadIndices.end(), sorter);
Run Code Online (Sandbox Code Playgroud)
namespace{
struct indicies_less_than
{
const SimpleGreedyMappingTechnique & mapping_tech;
indicies_less_than(const SimpleGreedyMappingTechnique & mapping_tech)
:mapping_tech(mapping_tech){}
bool operator()(int a, int b)
{
return mapping_tech.sortByWeights(a, b);
}
};
}
std::sort(payloadIndices.begin(), payloadIndices.end(), indicies_less_than(*this));
Run Code Online (Sandbox Code Playgroud)
如果被排序的类型比int你想要传递它们更复杂,const&以防止复制