Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Sorting objects based on two data members

I understand you can insert a user-defined class in to a std::vector and then overload the sorting mechanism so that it compares on a particular data member. However, how would you sort a std::vector<MyClass> where MyClass has two data members and you want to add a "second level" of sorting on the second data member? So sort on data member a and where a is equal, then sort on data member b?

like image 407
user997112 Avatar asked Sep 30 '13 21:09

user997112


1 Answers

Create a custom comparator using std::tuple

    #include <tuple>
   //..    
    struct comp
    {
      bool operator()(const MyClass& lhs, const MyClass& rhs) const
      {
        return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b);
      }
    };

It will use a first and then b second

like image 152
P0W Avatar answered Sep 24 '22 18:09

P0W