C++ sort函数对class类排序

sort是stl中一个经常用到的排序函数,可以对数组或类似数组(例如vector)的结构进行排序,默认为升序排序。


例如下面的代码对vec进行升序排序:

sort(vec.begin(),vec.end());


若想降序排序,则只需加greater即可:

sort(vec.begin(),vec.end(),gerater<int>());

若想对结构体进行排序,也很简单

第一种方法,重构运算符:

class Test
{
public:

    int a;
    int b;
    Test(int a,int b)
    {
        this->a = a;
        this->b = b;
    }
    bool operator <(const Test &other) const
    {
        return a<other.a;
    }
    bool operator >(const Test &other) const
    {
        return a>other.a;
    }
};
使用重构运算符之后即可直接调用sort进行排序。


第二种,定义compare函数进行排序:

bool compare(Test first,Test second)
{
    return first.a>second.a;
}
Test mytest;
sort(mytest.begin(),mytest.end(),compare)




  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值