2

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;
}
Azula
  • 457
  • 2
  • 5
  • 13
  • The parameters are `a` and `b`, which you both include in the sorting process, so what do you mean "[...] but on *all*."? The members of the `Employee` objects? – cadaniluk Mar 17 '16 at 09:31
  • Yes, I want sort vector considering not only name field, but also id, and secName. Maybe my English is not very good. – Azula Mar 17 '16 at 09:33
  • Then just include them in your `operator<` function and write appropriate `if`-clauses. The exact code depends on how you want to sort the `Employee`s in particular, so that's up to you. – cadaniluk Mar 17 '16 at 09:34
  • I don't know right way to do this. I've tried, but it not sorts appropriate. – Azula Mar 17 '16 at 09:36

2 Answers2

4

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;
}
Scintillo
  • 1,634
  • 1
  • 15
  • 29
2

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 &).

RyanCu
  • 516
  • 4
  • 12