gpt4 book ai didi

C++ 使用 qsort 对类数组进行排序

转载 作者:行者123 更新时间:2023-11-30 05:14:46 28 4
gpt4 key购买 nike

C++:我正在尝试按平均媒体对类(class)中存储的一些学生进行排序。

只有qsort,不要给我std::sort的建议,谢谢!

Qsort比较函数:

int cmp(Student *a, Student *b) {
return (int)(((Student *)b)->get_media() - ((Student *)a)->get_media());
}

qsort调用:

qsort(&tab, (size_t)n, sizeof(tab), (int(*)(const void*, const void*))cmp);

没有编译器错误,但不会排序。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class Student {
private:
char name[20];
char surname[20];
int *marks;
int group;
float avg_mark;
public:
Student()
{
char na[20], sur[20];
int group;
cout << "\nEnter name: ";
cin >> na;
cout << "\nEnter surname: ";
cin >> sur;
cout << "\nEnter group: ";
cin >> group;
init(na, sur, group);
}
~Student()
{
cout << "\ndestructor";
delete []marks;
}
void init(char *n, char *p, int gr)
{
strcpy(name, n);
strcpy(surname, p);
group = gr;
marks = new int[6];
for (int i = 0; i < 6; i++)
{
cout << "\nEnter mark " << i + 1 << ": ";
cin >> *(marks + i);
}
avg_mark = media();
}
float media()
{
int s = 0;
for (int i = 0; i < 6; i++)
s += marks[i];
return ((float)s / 6);
}
void set_name(char *n)
{
strcpy(name, n);
}
char* get_name()
{
return name;
}
void set_surname(char *p)
{
strcpy(name, p);
}
char* get_surname()
{
return surname;
}
int get_group()
{
return group;
}
float get_media()
{
return avg_mark;
}
};

int cmp(Student *a, Student *b);

int comparator(void *a, void *b) {
return (int)(((Student *)b)->get_media() - ((Student *)a)->get_media());
}



void main(void)
{
int n;
cout << "\nEnter n: ";
cin >> n;
Student *tab = new Student[n];
for (int i = 0; i < n; i++)
cout << i + 1 << ". " << tab[i].get_name() << " " << tab[i].get_surname() << " Group:" << tab[i].get_group() << " Average mark: " << tab[i].get_media() << endl;
//qsort(&tab[0], (size_t)n, sizeof(tab), (int*)cmp);
cout << endl;
qsort(&tab, (size_t)n, sizeof(tab), (int(*)(const void*, const void*))cmp);
for (int i = 0; i < n; i++)
cout << i + 1 << ". " << tab[i].get_name() << " " << tab[i].get_surname() << " Group:" << tab[i].get_group() << " Average mark: " << tab[i].get_media() << endl;
cin.ignore();
cin.get();
}

int cmp(Student *a, Student *b) {
return (int)(((Student *)b)->get_media() - ((Student *)a)->get_media());
}

最佳答案

qsort(&tab, (size_t)n, sizeof(tab), (int(*)(const void*, const void*))cmp);

&tab是指针tab的地址。您想要传递数组第一个元素的地址。那是 &tab[0] 或简单的 tab

此外,您需要传递 Student 对象的大小,而不是指针的大小。因此,将 sizeof(tab) 更改为 sizeof(Student)sizeof(*tab)。所以调用应该是这样的:

qsort(tab, (size_t)n, sizeof(*tab), (int(*)(const void*, const void*))cmp);

关于C++ 使用 qsort 对类数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43300450/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com