1. 程式人生 > >模擬EXCEL排序(struct和typedef struct)

模擬EXCEL排序(struct和typedef struct)

Excel可以對一組紀錄按任意指定列排序。現請編寫程式實現類似功能。 輸入格式:

輸入的第一行包含兩個正整數N(≤10​5​​) 和C,其中N是紀錄的條數,C是指定排序的列號。之後有 N行,每行包含一條學生紀錄。每條學生紀錄由學號(6位數字,保證沒有重複的學號)、姓名(不超過8位且不包含空格的字串)、成績([0, 100]內的整數)組成,相鄰屬性用1個空格隔開。 輸出格式:

在N行中輸出按要求排序後的結果,即:當C=1時,按學號遞增排序;當C=2時,按姓名的非遞減字典序排序;當C=3時,按成績的非遞減排序。當若干學生具有相同姓名或者相同成績時,則按他們的學號遞增排序。 輸入樣例:

3 1
000007 James 85
000010 Amy 90
000001 Zoe 60

輸出樣例:

000001 Zoe 60
000007 James 85
000010 Amy 90

答案:

#include <bits/stdc++.h>

using namespace std;
//const int N=1e5+10;//這裡必須是const型別的;

struct Student
{
    int number;
    char name[9];
    int score;
}S[100010];

bool cmp1(Student& a,Student& b)
{
    return a.number<b.number;
}

bool cmp2(Student& a,Student& b)
{
    return strcmp(a.name,b.name)?strcmp(a.name,b.name)<0:cmp1(a,b);
}

bool cmp3(Student& a,Student& b)
{
    return a.score!=b.score?a.score<b.score:cmp1(a,b);
}
int main()
{
    unsigned long long n;
    int c;
    scanf("%llu%d",&n,&c);
    for(int i=0;i<n;i++)
    {
        scanf("%d%s%d",&S[i].number,S[i].name,&S[i].score);//中間不需要空格,因為%s讀不進空格,同時%s那裡不需要&號
    }
    if(c==1)
    {
        sort(S,S+n,cmp1);
    }
    else if(c==2)
    {
        sort(S,S+n,cmp2);
    }
    else if(c==3)
    {
        sort(S,S+n,cmp3);
    }
    for(int i=0;i<n;i++)printf("%06d %s %d\n",S[i].number,S[i].name,S[i].score);
    return 0;

}

反思: 1、struct和typedef struct在C語言和c++中使用

C語言中定義結構體為

(1)先定義結構體型別,再定義結構體變數

struct student
{
    char no[20];       //學號
    char name[20];    //姓名
    char sex[5];    //性別
    int age;          //年齡
};
struct student stu1,stu2;

此時stu1,stu2=student結構體變數

stu1.no等

(2)定義結構體型別的同時定義結構體變數

struct student
{
    char no[20];       //學號
    char name[20];    //姓名
    char sex[5];    //性別
    int age;          //年齡
}stu1,stu2;

此時還可以繼續定義student結構體變數,如:

struct student stu3;

stu1.no等

(1)和(2)中的方法是直接定義了一個變數,可以直接使用比如stu1.no,stu1.name等

(3)定義兩個名字

typedef struct student
{
    char no[20];       //學號
    char name[20];    //姓名
    char sex[5];    //性別
    int age;          //年齡
}S;

這樣,結構體有兩個名字,一個是struct student,還有一個是S,不能直接 S . no ,S . name等,而是需要通過

S student1;
或者
struct student student1;

來定義一個結構體變數;

注意:在定義結構體陣列的時候,要標明陣列的長度比如S[100],而不能是S[N];

C++中的結構體

(1)

struct Student    
{
    int a;    
};

於是就定義了結構體型別Student,宣告變數時直接Student stu2; 這裡與C語言宣告變數的方式不同

(2)

struct   Student    
{
    int   a; 
}stu1; //stu1是一個變數

-------------------------------------

typedef struct Student2    
{
    int   a;   
}stu2; //stu2是一個結構體型別=struct Student

這裡與C語言相同;

使用時可以直接訪問stu1.a
但是stu2則必須先   stu2 s2;
然後               s2.a=10;