使用气泡排序从类中对 2D 字符和 Int 数组进行排序
Sorting a 2D Char and Int Array from class using bubble sort?
我正在尝试按降序对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];
我认为
你的问题就在这里:
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 对象,并应生成您正在寻找的输出
你必须复制
整个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;
}
}
}
}
问题是你需要交换对象,成绩只需要充当指导排序的关键,试试这个:
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
由于许多原因,这是错误的。
相关文章:
- 使用排序函数 c++ 对字符数组进行排序
- 非ASCII字符的词典排序
- 对向量<常量字符 *> 进行排序
- C++ MDC final-在字符类型的数组结构中按字母顺序对记录中的名称进行排序
- 按字母顺序排序字符数组,然后按长度排序
- 如何使用排序和比较这两个函数在 c++ 中对字符数组进行排序?
- 在字符串中对字符进行排序
- 多地图<矢量<int>>,字符>如何排序?
- C++ 从文件中读取字符,计算每个字符并进行排序
- 对包含整数和字符的字符串数组进行排序
- 使用气泡排序从类中对 2D 字符和 Int 数组进行排序
- 通过交换指针对字符数组进行排序,C++
- C++对2D字符数组进行气泡排序
- ASCII 艺术 - 按亮度级别对 ASCII 字符数组进行排序 (C/C++)
- 使用模板对字符串和字符进行排序
- 将字符串重新排序为没有连续相同字符的字符串
- C++ 对字符而不是整个字符串进行排序
- 正在对字符进行排序**
- 对包含特殊字符的 2D 数组进行排序 C++
- 排序的快速排序输出,给出一个附加字符