看懂STL中的sort排序

来源:互联网 发布:玩dnf网络冲突怎么办 编辑:程序博客网 时间:2024/05/17 08:56
该例子旨在说明对于自定义类型如何做排序:
方法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;}
运行结果:


原创粉丝点击