Sorting machine test scores of Tsinghua University (school grades Edition)

Title Description

Find and sort

Title: Enter any (user, results) sequence can be obtained from high to low or from low grade to high order, the same results
were treated according to the preceding entry arrangement rule.

Example:
Jack 70
peter 96
Tom 70
smith 67

High to low scores 
peter 96 
Jack 70 
Tom 70 
smith 67

From low to high

smith     67

jack      70 
Tom      70 
peter     96

Enter a description:

 

Enter multi-line, first enter the number you want to sort of person, then enter the sorting method 0 (in descending order) or 1 (in ascending order) were re-enter their names and achievements, separated by a space

Output Description:

 

Separated by a space between the specified manner in accordance with the output of the names and scores, names and scores

Example 1

Entry

3
0
fang 90
the 50
and 70

Export

fang 90
and 70
the 50
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct Student{
 string name;
 int grade;
 int order;
};
bool Compare1(Student x,Student y){ //降序
    if(x.grade==y.grade) {
        return x.order<y.order; //学号升序

    }
    else return x.grade>y.grade;  //成绩降序
}
bool Compare2(Student x,Student y){ //降序
    if(x.grade==y.grade) {
        return x.order<y.order;  //学号升序

    }
    else return x.grade<y.grade;  //成绩升序
}
int main(){
    int n;
    int i,flag; 
    while (scanf("%d%d",&n,&flag)!=EOF){
        Student arr[n];
        for(i=0;i<n;i++)
    {
   cin>>arr[i].name>>arr[i].grade;
   arr[i].order=i;
    }
    if(flag==0)
    sort(arr,arr+n,Compare1);
    else sort(arr,arr+n,Compare2);
    for(i=0;i<n;i++)
    {
        cout<<arr[i].name<<" "<<arr[i].grade<<endl;
    }
    }
    
    return 0;


}

Summary: ① By studying the sort function, there are three parameters can be found, where the first parameter is the initial position (the array name length, i.e. the first address), the second parameter as the end position, i.e., the length of the array name + n (arr + n), the third parameter is the default ascending, descending only suitable for a single liter of limitation. The return value is bool type, so custom Compare, Boolean return value must be a function, and when the return x <y represent ascending> for descending

           . ② through amendment of the last question, easily forgotten several points, one must remember to use while (scanf ( "% d% d", & n, & flag) = EOF!) To multiple inputs; 2. the Student ARR [] array defined in while, the size is determined by the n-input, otherwise prone array bounds

Published 23 original articles · won praise 5 · views 10000 +

Guess you like

Origin blog.csdn.net/xindada559/article/details/103971467