我正在尝试按降序排序int
和char
s(来自一个类)的数组。这些是学生姓名和成绩。
该类定义为:
class Student {
public:
char name[20];
int grades;
};
numCount
是记录数量的增量值。
void bubble_sort(Student theResults[], int numCount)
{
bool swapped = true;
while(swapped)
{
swapped = false;
for(int i=1;i<numCount;i++)
{
if(theResults[i-1].grades < theResults[i].grades)
{
int tempHold = theResults[i-1].grades;
theResults[i-1].grades = theResults[i].grades;
theResults[i].grades = tempHold;
swapped = true;
}
}
}
我遇到的问题是int
值(成绩)在循环后正确排序,但很难正确分配名称以与成绩匹配。
我使用了以下代码,但它不起作用,因为它显示了学生的不正确成绩。
char* title_temp = theResults[i-1].name;
theResults[i-1].name[20] = theResults[i].name[20];
theResults[i].name[20] = title_temp[20];
答案 0 :(得分:1)
问题是你需要交换对象,成绩只需要作为键来指导排序,试试这个:
void bubble_sort(Student theResults[], int numCount)
{
Student tempHold;
bool swapped = true;
while(swapped)
{
swapped = false;
for(int i=1;i<numCount;i++)
{
if(theResults[i-1].grades < theResults[i].grades)
{
tempHold = theResults[i-1]; //swap the objects, not just the grades.
theResults[i-1]= theResults[i];
theResults[i] = tempHold;
swapped = true;
}
}
}}
但是,如果您必须复制成员,那么除了交换成绩:
char temp[20];
strcpy(temp ,theResults[i-1].name);
strcpy(theResults[i-1].name,theResults[i].name);
strcpy(theResults[i].name,temp);
而不是使用
char* title_temp = theResults[i-1].name; // <-wrong
theResults[i-1].name[20] = theResults[i].name[20];//20 is invalid index
theResults[i].name[20] = title_temp[20]; //this is just 1 element out of the whole array
由于很多原因而导致错误。
答案 1 :(得分:1)
你必须使用循环一次复制整个char块,每个元素,或者你可以使用memcpy。
您还可以使用班级的浅色副本
void bubble_sort(Student theResults[], int numCount)
{
bool swapped = true;
while(swapped)
{
swapped = false;
for(int i=1;i<numCount;i++)
{
if(theResults[i-1].grades < theResults[i].grades)
{
Student tempHold = theResults[i-1];
theResults[i-1]= theResults[i];
theResults[i] = tempHold;
swapped = true;
}
}
}
}
答案 2 :(得分:1)
我认为你的问题在这里:
if(theResults[i-1].grades < theResults[i].grades)
{
int tempHold = theResults[i-1].grades;
theResults[i-1].grades = theResults[i].grades;
theResults[i].grades = tempHold;
swapped = true;
}
你真正想做的是
if(theResults[i-1].grades < theResults[i].grades)
{
Student tempHold = theResults[i-1];
theResults[i-1] = theResults[i];
theResults[i] = tempHold;
swapped = true;
}
在您更改之前是等级值而不是名称,这将切换整个Student对象并应生成您正在寻找的输出