繁体   English   中英

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

[英]Qsort() comparing the sum of struct ints

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

有没有办法对每个学生的价值求和然后使用 qsort? 我尝试编辑元素数量的值以及比较 function 的指针,但没有任何效果

#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;
}
int n; ... student stud[n];

在 C++ 中无效。 它正在使用编译器扩展,该扩展支持在 C++ 中使用 C 功能可变长度arrays。 VLA不是C++ 的一部分。 在 C++ 中使用std::vector<student>

你function:

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

无效 - a - b减去指向学生的指针,然后返回该值 - 该值与学生实际拥有的值无关。 取消引用指针并比较里面的值。 另外,不要删除 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 变量中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM