Sorting and carrying along all the information

Hi, I'm wondering why this piece of code isn't sorting and this is the same algorithm i've used before to sort a string of arrays. It runs and compiles but after it does so it gives me a error that my program has stopped working o_O.

My class is

1
2
3
4
5
6
7
8
9
class Student {
  public:
    string name;
    int score1;
    int score2;
    int score3;
    int total_score;
    string score_status;
};


Here is my function to sort the array. I have yet to begin to carry along all the information in the object. I'm a bit confused as where to go after this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void sort1(Student student[],int number)
{
    string tempstr;

    // sort the array
    for (int pos = 0; pos < number-1; pos++)
        for  (int cand = pos+1; cand < number; cand++)
            if (student[cand].info.first < student[pos].info.first)
            {
                tempstr = student[cand].info.first;
                student[cand].info.first = student[pos].info.first;
                student[pos].info.first = tempstr;
            }
    return;
}


Thank you
I don't see how that would compile. info isn't a member of Student. What is info?
Oh yes i put the old code. The corrected on is:

1
2
3
4
5
6
7
8
9
10
11
12
13
void sort1(Student student[],int number)
{
    string tempstr;

    // sort the array
    for (int pos = 0; pos < number-1; pos++)
        for  (int cand = pos+1; cand < number; cand++)
            if (student[cand].first < student[pos].first)
            {
                tempstr = student[cand].first;
                student[cand].first = student[pos].first;
                student[pos].first = tempstr;
            }
That still wouldn't work. first isn't a member of Student either.
1
2
3
4
5
6
7
8
9
class Student {
  public:
    string name;
    int score1;
    int score2;
    int score3;
    int total_score;
    string score_status;
};




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void sort1(Student student[],int number)
{
    string tempstr;

    // sort the array
    for (int pos = 0; pos < number-1; pos++)
        for  (int cand = pos+1; cand < number; cand++)
            if (student[cand].name < student[pos].name)
            {
                tempstr = student[cand].name;
                student[cand].name = student[pos].name;
                student[pos].name = tempstr;
            }
    return;
}
You should find something better than a bubble sort.

In any case, to sort a list of things, you must exchange the entire thing, not just part of it. What your swap (lines 10 through 12) does is just cheat the better-scoring student by moving his name onto a poorly-performing student's scores.

Swap a student:

1
2
3
4
5
6
7
Student temp;

...

    temp = student[cand];
    student[cand] = student[pos];
    student[pos] = temp;

BTW, the variable names "cand" and "pos" are not that great (IMHO).

Hope this helps.
Topic archived. No new replies allowed.