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

查找和排序

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

输入描述:

输入多行,先输入要排序的人的个数,然后输入排序方法0(降序)或者1(升序)再分别输入他们的名字和成绩,以一个空格隔开。
按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开

示例1:
输入

3
0
fang 90
yang 50
ning 70

输出

fang 90
ning 70
yang 50

考察内容:结构体排序

#include <bits/stdc++.h>
using namespace std;
#define MAXSIZE 100000
struct Student
{
    string name;
    double score;
    int index;
};

int cmp2(Student a, Student b)
{//成绩从大到小排序
    if(a.score == b.score)
        return a.index < b.index;
    return a.score < b.score;
}

int cmp1(Student a, Student b)
{//成绩从小到大排序
    if(a.score == b.score)
        return a.index < b.index;
    return a.score > b.score;
}
int main()
{
    int n, m;
    while(scanf("%d %d", &n, &m)!=EOF)
    {
        Student *s = new Student[MAXSIZE];
        for(int i = 0; i < n; i++)
        {
            cin>>s[i].name>>s[i].score;
            s[i].index = i;//录入顺序
        }
        if(m == 0)
            sort(s, s+n, cmp1);
        else
            sort(s, s+n, cmp2);
        for(int i = 0; i < n; i++)
            cout<<s[i].name<<" "<<s[i].score<<endl;
    }
    return 0;
}

发布了29 篇原创文章 · 获赞 4 · 访问量 4685

猜你喜欢

转载自blog.csdn.net/onion___/article/details/104859088