我想使用 qsort() 对学生结构体的数组进行排序。首先按年级排序,然后尝试 再次使用学生证。
我发现两个问题。
结果
Sorted by grades
Ver Grade: 28
Alistair Grade: 68
Fred Grade: 70
Erin Grade: 75
Lesli Grade: 78
Belind Grade: 81
Sash Grade: 84
Tom Grade: 87
Aretha Grade: 98
Candy Grade: 100
代码
#include <iostream>
#include <string>
using namespace std;
struct student {
int grade;
int studentID;
string name;
};
const int ARRAY_SIZE = 10;
student studentArray[ARRAY_SIZE] = {
{87, 10001, "Fred"},
{28, 10002, "Tom"},
{100, 10003, "Alistair"},
{78, 10004, "Sasha"},
{84, 10005, "Erin"},
{98, 10006, "Belinda"},
{75, 10007, "Leslie"},
{70, 10008, "Candy"},
{81, 10009, "Aretha"},
{68, 10010, "Veronica"}
};
// Comparator Function
int compareFunc(const void* voidA, const void* voidB)
{
student* studentA = (student*) voidA;
student* studentB = (student*) voidB;
return (studentA->grade - studentB->grade);
}
int main()
{
// Use qsort to sort an array of our student struct
qsort(studentArray, ARRAY_SIZE, sizeof(student), compareFunc);
// First sort by grade
cout << "Sorted by grades \n";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cout << studentArray[i].name << " Grade: " << studentArray[i].grade << '\n';
}
// Second sort by student ID
不太确定我哪里错了,感谢你的想法