使用基本方法对结构进行排序

时间:2013-10-25 06:12:21

标签: c++ c

这是一个程序,它总计每个学生的标记并对总数进行排序,但不会交换其他参数的顺序,如学生姓名和学科标记。如何在保持总标记作为排序基础的同时对整个结构进行排序?我不想使用任何内置函数,而是通过基本方法来完成。

#include<stdio.h>
#include<conio.h>
struct stnd
{
   int sub[20];
   char name[20];
   int total;
}
stnd[20];
main()
{
    int i, j, n=4, m=4,k;
    for(i=0; i<n; i++)
        for(j=0; j<m; j++)
            scanf("%d",&stnd[i].sub[j]);
    for(i=0; i<n; i++)
        scanf(" %s",stnd[i].name);
    for(i=0; i<n; i++)
    {
        stnd[i].total=0;
        for(j=0; j<m; j++)
            stnd[i].total=stnd[i].total+stnd[i].sub[j];
    }

    for(i=0; i<n; i++)
    {
        for(j=i+1; j<n; j++)
        {
            if(stnd[i].total<stnd[j].total)
            {
                k=stnd[i].total;
                stnd[i].total=stnd[j].total;
                stnd[j].total=k;
            }
        }
    }

    printf("Rank\t Chin\t Math\t Eng\t Comp\t total\t name\n");
    for(i=0; i<n; i++)
    {
        printf("%d\t",i+1);
        for(j=0; j<m; j++)
        printf("%d\t",stnd[i].sub[j]);
        printf("%d\t",stnd[i].total);
        printf("%s\t\n",stnd[i].name);

    }
    getch();
}

1 个答案:

答案 0 :(得分:2)

在您交换的功能中,只需交换结构而不是总数:

// Where you declare k, declare it as a struct stnd
struct stnd k;

// Where you swap, just swap the structures, not the totals
k = stnd[i];
stnd[i]  stnd[j];
stnd[j] = k;

当您设置struct stnd时,它会对您正在复制的对象进行按位复制,这正是排序所需的内容。