如何重载运算符<用于对象的排序方法? [英] How overload operator < for sort method for objects?
本文介绍了如何重载运算符<用于对象的排序方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有这个对象
class Employee{
int id;
string name;
string secName;
}
我的主要是:
int main(){
vector<Employee> vec = {Employee(1, "Andy", "Good"), Employee(5, "Adam", "Bad"), Employee(2, "Some", "Employee")}
sort(vec.begin(), vec.end())
}
当我有一个要排序的参数时,我知道向量的重载排序方法.就像:
I know how overload sort method for vector when I have one parameter for sorting. It's like:
bool operator<(Employee a, Employee b ){
if (a.name<b.name) return true;
else return false;
}
但是关键是我不仅对一个参数进行排序,而且对所有参数进行排序.那么我应该如何更改重载方法?
But the point is that I have sort not only on one parameter, but on all. So how should I change overloading method?
我已经尝试过这种方法,但是没有用.
I've tried this way, but it doesn't work.
bool operator<(Employee a, Employee b)
{
if (a.id < b.id)
if (a.name < b.name)
if (a.surname<b.surname)return true; else return false;
else return false;
else return false;
}
推荐答案
如果要主要按id排序,其次是按名称排序,然后按secName进行三级排序,这应该可以:
If you want to sort primarily by id, secondarily by name and tertiary by secName this should work:
bool operator<(Employee a, Employee b)
{
if (a.id < b.id) return true;
if (a.id > b.id) return false;
if (a.name < b.name) return true;
if (a.name > b.name) return false;
if (a.secName < b.secName) return true;
return false;
}
这篇关于如何重载运算符<用于对象的排序方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文