看懂STL中的sort排序

该例子旨在说明对于自定义类型如何做排序:
方法1:重载"<"或者">"运算符,对于less函数,对应重载<,对于greater函数,对应重载>;
方法2:采用自己写的比较函数,将函数名当做形参传入sort函数中去,如:sort(v.begin(),v.end(),MysortFunction);


代码测试:

#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>

using namespace std;

class student{
public:
    student(const string &a, int b) :name(a), score(b){}
    string name;
    int score;

    bool operator < (const student &m)const   //重载小于号
    {
        return score < m.score;
    }
    bool operator > (const student &m)const   //重载大于号
    {
        return score > m.score;
    }
};

//自定义比较函数
bool MySortFunction(const student &a, const student &b)
{
    return a.score < b.score;
}

int main() {
    vector< student> vect;
    student st1("Tom", 74);
    vect.push_back(st1);
    st1.name = "Jimy";
    st1.score = 56;
    vect.push_back(st1);
    st1.name = "Mary";
    st1.score = 92;
    vect.push_back(st1);
    st1.name = "Jessy";
    st1.score = 85;
    vect.push_back(st1);
    st1.name = "Jone";
    st1.score = 56;
    vect.push_back(st1);
    st1.name = "Bush";
    st1.score = 52;
    vect.push_back(st1);
    st1.name = "Winter";
    st1.score = 77;
    vect.push_back(st1);
    st1.name = "Andyer";
    st1.score = 63;
    vect.push_back(st1);
    st1.name = "Lily";
    st1.score = 76;
    vect.push_back(st1);
    st1.name = "Maryia";
    st1.score = 89;
    vect.push_back(st1);
    cout << "---------------原有数据------------------" << endl;
    for (int i = 0; i < vect.size(); i++)
        cout << vect[i].name << ":\t" << vect[i].score << endl;

    cout << "---------------重载小于号升序排序------------" << endl;
    stable_sort(vect.begin(), vect.end(), less<student>());
    for (int i = 0; i < vect.size(); i++)
        cout << vect[i].name << ":\t" << vect[i].score << endl;
    
    cout << "---------------重载大于号降序排序------------" << endl;
    stable_sort(vect.begin(), vect.end(), greater<student>());
    for (int i = 0; i < vect.size(); i++)
        cout << vect[i].name << ":\t" << vect[i].score << endl;
    
    cout << "---------------自己写升序比较函数------------" << endl;
    stable_sort(vect.begin(), vect.end(), MySortFunction);
    for (int i = 0; i < vect.size(); i++) 
        cout << vect[i].name << ":\t" << vect[i].score << endl;
   
    return 0;
}
运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值