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;
}
4
  • 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? Commented Mar 17, 2016 at 9:31
  • Yes, I want sort vector considering not only name field, but also id, and secName. Maybe my English is not very good. Commented Mar 17, 2016 at 9: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 Employees in particular, so that's up to you. Commented Mar 17, 2016 at 9:34
  • I don't know right way to do this. I've tried, but it not sorts appropriate. Commented Mar 17, 2016 at 9:36

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. It is exactly what I've wanted. Thanks)
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 &).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.