Azula
Azula

Reputation: 467

How overload operator < for sort method for objects?

I have this object, for example

 class Employee{
    int id;
    string name;
    string secName;
    }

My main is :

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;
}

Upvotes: 2

Views: 12122

Answers (2)

RyanCu
RyanCu

Reputation: 566

If you want to sort primarily by id, secondarily by name and tertiarily by secName, you could use this trick involving std::tie:

#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);
}

It's also best for the function parameters to be passed in as const-refs (const &).

Upvotes: 2

Scintillo
Scintillo

Reputation: 1704

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;
}

Upvotes: 4

Related Questions