C++ STL 容器vector元素排序实例

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class student{
public:
    student(const string& a,double b):name(a),score(b){

    }
    string name;
    double score;
    bool operator<(const student& m)const{
        return score<m.score;
    }
};

bool name_sort_less(const student& m,const student& n){
    return m.name<n.name;
}

bool name_sort_greater(const student& m,const student& n){
    return m.name>n.name;
}

bool score_sort(const student& m,const student& n){
    return m.score>n.score;
}

void print(const student& s){
    cout<<s.name<<"    "<<s.score<<endl;
}

void Original(vector<student>& V){
    student st1("Tom",74);
    V.push_back(st1);
    st1.name="Jimy";
    st1.score=56;
    V.push_back(st1);
    st1.name="Jone";
    st1.score=66;
    V.push_back(st1);
    st1.name="Bush";
    st1.score=86;
    V.push_back(st1);
    st1.name="Winter";
    st1.score=99;
    V.push_back(st1);
    st1.name="Summer";
    st1.score=100;
    V.push_back(st1);
    st1.name="Cool";
    st1.score=88;
    V.push_back(st1);
    st1.name="Spring";
    st1.score=72;
    V.push_back(st1);
}

int main()
{
    vector<student> vect;
    Original(vect);
    cout<<"----Before sorted.----"<<endl;
    for_each(vect.begin(),vect.end(),print);
    //调用operator<
    sort(vect.begin(),vect.end());
    cout<<"----After sorted by sore.----"<<endl;
    for_each(vect.begin(),vect.end(),print);
    //name从小到大排序
    sort(vect.begin(),vect.end(),name_sort_less);
    cout<<"----After sorted by name.----"<<endl;
    for_each(vect.begin(),vect.end(),print);
    sort(vect.begin(),vect.end(),score_sort);
    cout<<"----After sorted by score.----"<<endl;
    for_each(vect.begin(),vect.end(),print);
    //按name从大到小排序
    sort(vect.begin(),vect.end(),name_sort_greater);
    cout<<"----After sorted by name.----"<<endl;
    //输出排序结果
    for_each(vect.begin(),vect.end(),print);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ibelievesunshine/article/details/80214660
今日推荐