2012-12-06 40 views
0

我想按降序对intchar(从一个类)的数组进行排序。这些是学生的姓名和成绩。使用冒泡排序从类中排序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]; 

回答

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; 
} 

之前所有你改变的是成绩值而不是名字,这将切换整个学生对象,并应该亲duce你正在寻找的输出

+0

Siegester,谢谢。代码完美工作。谢谢你的帮助。 – MacKey

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 

这是错误的,由于许多原因。

+0

axiom,优秀:D同样工作就像一个魅力。感谢您的帮助和建议。 PS抱歉只能将1标记为正确答案,并且完成了第一篇文章,即使所有三篇文章都是正确的。抱歉。 – MacKey

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; 
      } 
     } 
    } 
} 
+0

Nico,上面的代码也很完美。感谢您的时间和help.PS对不起,只能标记1作为正确的答案,我做了第一篇文章,即使所有三个帖子都是正确的。抱歉。 – MacKey