C ++根据两个数据成员对对象进行排序 [英] C++ Sorting objects based on two data members

查看:152
本文介绍了C ++根据两个数据成员对对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您可以将用户定义的类插入到std::vector中,然后重载排序机制,以便在特定数据成员上进行比较.但是,如何对std::vector<MyClass>进行排序,其中MyClass有两个数据成员,并且要在第二个数据成员上添加第二级"排序?因此,对数据成员a排序,其中a相等,然后对数据成员b排序?

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?

推荐答案

使用 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);
      }
    };

它将首先使用a,然后使用b

It will use a first and then b second

这篇关于C ++根据两个数据成员对对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆