如何進行結構體排序


結構體排序的幾種情況

1.一個結構體中有三個元素,按照其中一個元素進行升序排列:

先定義一個結構體:

struct node 
{
    int s;
    int t;
    int w;
}a[1005];

然后寫排序代碼:

int cmp(node a, node b)
{
    return a.s > b.s;
}

在main函數里面用sort進行排序:

sort(a, a+ n, cmp);

2:排序要求:按分數從高到低輸出上線考生的考號與分數,其間用1空格分隔。若有多名考生分數相同,則按他們考號的升序輸出。

定義一個結構體:

struct  Student
{
    char  str[30];   //考生准考證號
    char  num[20];  //存題號
    int  sum;  // 考生的最后得分
}student[1010];

然后寫排序代碼:

int cmp(Student a, Student b)
{
    if(a.sum == b.sum)
    {
        return a.str < b.str;
    }
    return a.sum >b.sum;
}
sort(student, student+n, cmp);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM