C++ Sorting objects based on two data members

2019-01-26 14:22发布

问题:

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?

回答1:

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