0

int(クラスの) andcharの配列を降順でソートしようとしています。生徒の名前と成績です。

クラスは次のように定義されます。

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];
4

3 に答える 3

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;
            }
        }
    }
}
于 2012-12-06T16:54:04.433 に答える
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オブジェクト全体が切り替わり、探している出力が生成されます。

于 2012-12-06T16:55:07.323 に答える
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

これは多くの理由で間違っています。

于 2012-12-06T16:52:30.407 に答える