我想按降序對int
和char
(從一個類)的數組進行排序。這些是學生的姓名和成績。使用冒泡排序從類中排序2D Char和Int數組?
的類定義爲:
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];
Siegester,謝謝。代碼完美工作。謝謝你的幫助。 – MacKey