欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

看懂STL中的sort排序

程序员文章站 2024-01-26 12:49:16
...
该例子旨在说明对于自定义类型如何做排序:
方法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;
}
运行结果:

看懂STL中的sort排序

相关标签: STL 排序 sort