如何重载运算符 < for 对象的排序方法?
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())
}
我知道当我有一个排序参数时如何重载向量的排序方法。就像:
bool operator<(Employee a, Employee b ){
if (a.name<b.name) return true;
else return false;
}
但重点是我不仅对一个参数进行了排序,而且对所有参数进行了排序。那么我应该如何更改重载方法呢?
这个方法我试过了,还是不行。
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 排序,这应该可行:
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;
}
如果您想主要按 id
排序,其次按 name
排序,第三按 secName
排序,您可以使用涉及 std::tie
:[=16= 的技巧]
#include <tuple>
// ...
bool operator<(const Employee& lhs, const Employee& rhs)
{
return std::tie(lhs.id, lhs.name, lhs.secName)
< std::tie(rhs.id, rhs.name, rhs.secName);
}
最好将函数参数作为 const-refs (const &
) 传入。
我有这个对象,例如
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())
}
我知道当我有一个排序参数时如何重载向量的排序方法。就像:
bool operator<(Employee a, Employee b ){
if (a.name<b.name) return true;
else return false;
}
但重点是我不仅对一个参数进行了排序,而且对所有参数进行了排序。那么我应该如何更改重载方法呢?
这个方法我试过了,还是不行。
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 排序,这应该可行:
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;
}
如果您想主要按 id
排序,其次按 name
排序,第三按 secName
排序,您可以使用涉及 std::tie
:[=16= 的技巧]
#include <tuple>
// ...
bool operator<(const Employee& lhs, const Employee& rhs)
{
return std::tie(lhs.id, lhs.name, lhs.secName)
< std::tie(rhs.id, rhs.name, rhs.secName);
}
最好将函数参数作为 const-refs (const &
) 传入。