STL中的自定义排序

一 链表list的自定义排序

  如何实现链表保存学生对象,包括名字(string)和学号(int),按照学号升序排序?

//list的sort

#include<bits/stdc++.h>
using namespace std;
class stu
{
public:
    string name;
    int number;
    stu(int i,string s)
    {
        name=s;
        number=i;
    }
    void print()
    {
        cout<<number<<" "<<name<<endl;
    }
};
struct cmp
{
    bool operator()(stu & A,stu &B)
    {
        return A.number<B.number;
    }
};
int main()
{
    stu X(1,"X");
    stu Y(2,"Y");
    stu Z(3,"Z");
    list<stu>V;
    V.push_back(X);
    V.push_back(Y);
    V.push_back(Z);
    //sort(V.begin(),V.end(),cmp());
    V.sort(cmp());
    list<stu>::iterator i;
    for(i=V.begin();i!=V.end();i++)
    {
        cout<<(i->number)<<" "<<(i->name)<<endl;
        //i->print();
    }
}

 

posted @ 2019-11-13 15:32  TheDa  阅读(232)  评论(0编辑  收藏  举报