如何在c++中使用sort()使用自定义排序成员功能?
我有一个问题,要将比较函数传递到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
并指向指向sortbyWeaights
。
是否可以使用类的成员函数进行排序?如果是这样,我如何实现?
I have a question about passing the comparison function to sort()
.
What I want to do is define a sort()
function that takes into account for its calculation a member variable of the class that I want to do the sorting in.
Basically, my code looks like this (simplified to only show the relevant parts):
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);
}
This code doesn't compile, it gives the following error:
error: reference to non-static member function must be called
and points to sortByWeights
.
Is it even possible to use a member function of a class for sorting? If it is, how I can implement this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,但是通常我会鼓励只使用适当的函子或lambda:
使用lambda:
或者使用
std :: mem_fn
:或者使用functor:
注意:
如果被排序的类型比
int
更复杂,您肯定想通过const&amp;
通过它们来防止复制It is, but in general I would encourage just using a proper functor or a lambda:
Using a lambda:
Alternatively using
std::mem_fn
:Alternatively using a functor:
Note:
if the types being sorted were anything more complicated than an
int
you would definitely want to pass them byconst&
to prevent copying如Mgetz所述,可以使用函子。函子的示例:
As mentioned by Mgetz, a functor can be used. Example of functor: