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

标签 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();
}

最佳答案

在你要交换的函数中,只交换结构而不是总数:

// 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 时,它会按位复制您正在复制的对象,这正是您排序所需要的。

关于c++ - 使用基本方法对结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19582341/

相关文章:

c++ - 为什么这个shared_ptr vector 的定义可以通过编译器的检查呢?

我们可以在 printf 中传递指针吗?

c - 函数返回错误类型 C

c - 为什么 tab[i][j] = "value"段错误

c++ - fwrite() 与 write() 存在磁盘缓存

c++ - 为arm编译qwt

c++ - (C++) 当两个类使用彼此的对象时,使用其他类的对象作为类中的参数

c - 我怎样才能在 ansi C90 中捕获运行时错误

c++ - 卡萨布兰卡:在 linux centos 上的汇编错误 gcc 4.8.1

c++ - 为什么我在编译 OpenVino 示例时遇到此错误