初学者代码改良

菜鸟求助代码改良
结构体问题:
struct 结构体代码改良.我写了一个小的程序.来展现分数排行,哪位大小能帮我改下,以分数score的分数最高,排行第一,ranking作为排行.我写的代码是:
#include<stdio.h>
int main()
{
    struct Record     //分数
    {
        int ranking;  //排行
        char *name;  //姓名
        int score;
    };
    struct Record num[3]={
        {1,"jack",5000},
        {2,"Tim",4100},
        {3,"rose",3500}
    };
    
    num[0].ranking=4;
    
    for(int a=0;a<3;a++)
    {
        printf("%d %s %d \n",num[a].ranking,num[a].name,num[a].score);
    }
    return 0;
}

分数最高者:ranking为1,以此类推
------解决思路----------------------
#include<stdio.h>
int main()
{
    struct Record     //分数
    {
        int ranking;  //排行
        char *name;  //姓名
        int score;
    };
    struct Record num[3]={
        {1,"jack",5000},
        {2,"Tim",4100},
        {3,"rose",3500}
    };
    struct Record t;

    num[0].ranking=4;

    int a,b;

    for(a=0;a<3-1;a++)
    for(b=a+1;b<3;b++)
    if (num[a].score<num[b].score) {
        t=num[a];num[a]=num[b];num[b]=t;
    }

    b=1;
    for(a=0;a<3;a++) num[a].ranking=b++;

    for(a=0;a<3;a++)
    {
        printf("%d %-5s %d\n",num[a].ranking,num[a].name,num[a].score);
    }

    return 0;
}
//1 jack  5000
//2 Tim   4100
//3 rose  3500
//

------解决思路----------------------
结构中ranking看起来没用, 排序好了就自然定了, 调用qsort就好了
------解决思路----------------------
这样写:


#include<stdio.h>
#include <algorithm>

int main()
{
struct Record     //分数
{
int ranking;  //排行
char *name;  //姓名
int score;
};
struct Record num[3]={
{1,"jack",5000},
{2,"Tim",4100},
{3,"rose",3500}
};
class Compare
{
public:
bool operator()(const Record& r1, const Record& r2)
{
return r1.score > r2.score;
}
};

std::sort(num, num + 3, Compare());

for(int a=0;a<3;a++)
{
num[a].ranking = a + 1;
printf("%d %s %d \n",num[a].ranking,num[a].name,num[a].score);
}
return 0;
}

------解决思路----------------------
引用:
这样写:


#include<stdio.h>
#include <algorithm>

int main()
{
struct Record     //分数
{
int ranking;  //排行
char *name;  //姓名
int score;
};
struct Record num[3]={
{1,"jack",5000},
{2,"Tim",4100},
{3,"rose",3500}
};
class Compare
{
public:
bool operator()(const Record& r1, const Record& r2)
{
return r1.score > r2.score;
}
};

std::sort(num, num + 3, Compare());

for(int a=0;a<3;a++)
{
num[a].ranking = a + 1;
printf("%d %s %d \n",num[a].ranking,num[a].name,num[a].score);
}
return 0;
}


这是用STL中的sort来实现的
可以扩展到数组中元素更多的情况,需要将std::sort(num, num + 3, Compare()); 这里3改成数组元素个数