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

Qsort() comparing the sum of struct ints

本文关键字:整数 结构体 比较 Qsort      更新时间:2023-10-16

我有一个程序,旨在接收由他们的名字和 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;
}
int n;
...
student stud[n];

在C++中无效。它使用编译器扩展,允许在C++中使用 C 功能可变长度数组。VLA不是C++的一部分。在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减去指向学生的指针,然后返回该值 - 该值与学生实际拥有的值无关。取消引用指针并比较其中的值。另外,不要删除恒常性。

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