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.
And a want to sort log
so I have:
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. You need:
bool sortFunction(const CMail& a, const CMail& b){
return (a.CompareByTimeStamp(b) < 0);
}
Which also means your signature for CompareByTimeStamp
must be:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.