简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM