在 C++ 中使用 qsort 对结构体数组进行排序

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

我想使用 qsort() 对学生结构体的数组进行排序。首先按年级排序,然后尝试 再次使用学生证。

我发现两个问题。

  1. 虽然成绩排序正确(升序),但为什么成绩与各自的学生姓名不对应?
  2. 为什么有些学生的名字被删掉了(比如“Ver”而不是“Veronica”?

结果

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

不太确定我哪里错了,感谢你的想法

c++ arrays struct qsort
1个回答
1
投票

正如@john 上面评论的那样,你不能将

qsort
与不可普通复制的类型一起使用(而你的则不是,因为它包含
std::string
)。

您可以使用

std::sort

您还可以使用 lambda 代替外部比较函数:

#include <algorithm>

// ...

std::sort(std::begin(studentArray), 
          std::end(studentArray),
          [](student const& a, student const& b) { return (a.grade > b.grade); });
© www.soinside.com 2019 - 2024. All rights reserved.