成绩排序

查找和排序

题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
      都按先录入排列在前的规则处理。

   例示:
   jack      70
   peter     96
   Tom       70
   smith     67

   从高到低  成绩            
   peter     96    
   jack      70    
   Tom       70    
   smith     67    

   从低到高

   smith     67  

   Tom       70    
   jack      70    
   peter     96      

输入描述:

输入多行,先输入要排序的人的个数,然后分别输入他们的名字和成绩,以一个空格隔开

输出描述:

按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开

示例1

输入

复制
3
0
fang 90
yang 50
ning 70

输出

复制
fang 90
ning 70
yang 50

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct student
{
    string name;
    int score;
};
bool cmp0(const student &a, const student &b)
{
    // 从高到低排序
    return a.score > b.score;
}
bool cmp1(const student &a, const student &b)
{
    // 从低到高排序
    return a.score < b.score;
}
int main()
{
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    int N, type;
    while(cin >> N >> type)
    {
        vector<student> stud(N);
        for(int i = 0; i < N; i ++)
        {
            cin >> stud[i].name >> stud[i].score;
        }
        if(type == 0)
            stable_sort(stud.begin(), stud.end(), cmp0);
        else
            stable_sort(stud.begin(), stud.end(), cmp1);
        for(int i = 0; i < N; i ++)
        {
            cout << stud[i].name << " " << stud[i].score << endl;
        }
    }
    return 0;
}


原文地址:https://www.cnblogs.com/zhoumin6012/p/9928462.html