【问题标题】:Qsort() comparing the sum of struct intsQsort() 比较结构整数的总和
【发布时间】:2020-05-31 06:37:57
【问题描述】:

我有一个程序旨在接收由他们的姓名和 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;
}

【问题讨论】:

  • 作为新用户,请拨打tour阅读How to Ask。关于你的问题,很明显你需要调整你的 compare() 函数,所以我不确定你在问什么。顺便说一句:编译带有警告并提交您的代码(一旦它工作)在 codereview.stackexchange.com 上进行审查。有几件事情迟早会导致问题。

标签: c++ struct qsort


【解决方案1】:
int n;
...
student stud[n];

在 C++ 中无效。它使用了一个编译器扩展,可以在 C++ 中使用 C 特性 variable length arrays。 VLA 不是 C++ 的一部分。在 C++ 中使用 std::vector&lt;student&gt;

你的作用:

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 变量中。

【讨论】:

  • 它们按totalScore 降序排列。我想你想要b-&gt;totalScore - a-&gt;totalScore
猜你喜欢
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
  • 2022-01-23
  • 2018-03-26
  • 1970-01-01
相关资源
最近更新 更多