[英]Sort function for std:sort with & parametr c++
I want to use reference to my instance as a parameter of sort function. 我想将对实例的引用用作排序函数的参数。
I have vector<CMail> log
, in class CMail
have function which compare as I want. 我有vector<CMail> log
,在类CMail
有需要比较的功能。
And a want to sort log
so I have: 和想要排序log
所以我有:
bool sortFunction(CMail a, CMail b){
return (a.CompareByTimeStamp(b) < 0) ? true : false;
}
and then 接着
sort(log.begin(), log.end(), sortFunction);
It works fine. 工作正常。 But can I have parameters of function as a reference like this? 但是我可以像这样将功能参数作为参考吗?
bool sortFunction(CMail &a, CMail &b){
...
}
When I did this, my code didn't compile. 当我这样做时,我的代码没有编译。
How can I do this? 我怎样才能做到这一点?
In short: const
ness. 简而言之: const
。 You need: 你需要:
bool sortFunction(const CMail& a, const CMail& b){
return (a.CompareByTimeStamp(b) < 0);
}
Which also means your signature for CompareByTimeStamp
must be: 这也意味着您对CompareByTimeStamp
的签名必须为:
int CompareByTimeStamp(const Cmail& other) const; // (inside class Cmail {...};)
// ^ b is const ^ a is const
See here . 看这里 。 This is all because comparing two objects should not change them. 这是因为比较两个对象不应更改它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.