Qsort()比较结构整数的总和

问题描述 投票:0回答:1

我有一个程序,旨在容纳由他们的姓名和3个测试分数组成的n个结构的学生,并且必须使用qsort()根据他们的总分数以降序输出它们。虽然我已经能够对它们进行排序,但是它们仅按其第一个值进行排序。

是否有一种方法可以对每个学生的值求和然后使用qsort?我尝试编辑元素数量的值以及比较函数的指针,但是没有任何作用

#include <cstdlib>
#include <iostream>

using namespace std;

typedef struct {
    char name[16];
    int chineseScore;
    int mathScore;
    int englishScore;
    int totalScore;
} student;

int compare(const void* p1, const void* p2) {
    student *a = (student *)p1;
    student *b = (student *)p2;
    return (a - b);
}

int main() {
    //gets input
    int n;
    do{
        cin >> n;
    }while (n < 1 || n > 10);
    student stud[n];
    for (int i = 0; i < n; i++){
        cin >> stud[i].name >> stud[i].chineseScore >> stud[i].mathScore >> stud[i].englishScore;
        stud[i].totalScore = stud[i].chineseScore + stud[i].mathScore + stud[i].englishScore;
    }
    //sorts array with qsort()
    qsort(stud, n, sizeof(student), compare);
    //prints result
    for (int i = 0; i < n; i++){
        cout << stud[i].name << ' '<< stud[i].chineseScore <<' '<< stud[i].mathScore <<' '<< stud[i].englishScore<< endl;
     }

    return 0;
}
c++ struct qsort
1个回答
0
投票
int n;
...
student stud[n];

在C ++中无效。它正在使用编译器扩展,该扩展允许在C ++中使用C功能variable length arrays。 VLA是C ++的not部分。在C ++中使用std::vector<student>

您的职能:

int compare(const void* p1, const void* p2) {
    student *a = (student *)p1;
    student *b = (student *)p2;
    return (a - b);
}

是无效的-a - b减去pointers给学生,然后返回该值-该值与学生实际拥有的值无关。解引用指针并比较其中的值。另外,请勿删除const-ness。

int compare(const void* p1, const void* p2) {
    const student *a = (const student*)p1;
    const student *b = (const student*)p2;
    return a->chineseScore - b->chineseScore;
}

是否有一种方法可以对每个学生的值求和然后使用qsort?

声明一个变量,该变量将保存总和并将其初始化为零。然后遍历学生数组,并将学生中某物的值添加到您先前声明的sum变量中。]

© www.soinside.com 2019 - 2024. All rights reserved.