-1

I'm trying to print a player and their score from highest score to lowest. I can get it to descend, but it does not correlate to the correct player name.

With the following code:

void showPlayers() {
int desc;
for (int i = 0; i < pointer; i++) {
    for (int j = 0; j < pointer; j++) {
        if (scores[i] < scores[j]) {    //flipping comparison operator descends data, 
                                        //but either increments/decrements each player's 
                                        //score
            desc = scores[i];
            scores[i] = scores[j];
            scores[j] = desc;
        }
    }
}
for (int i = 1; i < pointer; i++) {
    cout << playerNames[i] << "\t" << scores[i] << "\n";
}
cout << endl;
}

I am receving an output like:

Player1    20
Player2    30
Player3    40


for (int i = 0; i < pointer; i++) {
    for (int j = 0; j < pointer; j++) {
        if (scores[i] > scores[j]) {
            swap(scores[i], scores[j]); 
        }
    }
}
for (int i = 0; i < pointer; i++) {
    for (int j = 0; j < pointer; j++) {
        if (playerNames[i] > playerNames[j]) {
            swap(playerNames[i], playerNames[j]);
        }
    }
}
for (int i = 0; i < pointer; i++) {
    cout << playerNames[i] << "\t" << scores[i] << "\n";
}
sethFrias
  • 73
  • 1
  • 6
  • 1
    You need to swap the player names too. Also `std::swap` might help. – Abhyudaya Sharma Feb 22 '19 at 03:44
  • 1
    Consider using a single array of a structure containing both player name and player score. If the name and the score are stored as one unit, they can easily be swapped as one unit. – user4581301 Feb 22 '19 at 03:46
  • I don't think this would help me because I'm utilizing the names and scores separately in other functions. – sethFrias Feb 22 '19 at 03:57

1 Answers1

2

Use this inside the if statement:

std::swap(scores[i], scores[j]);
std::swap(playerNames[i], playerNames[j]);

You are not swapping the corresponding playerNames when you're swapping the scores. Also, it is much more readable if you use std::swap.

Abhyudaya Sharma
  • 1,173
  • 12
  • 18
  • I realize I also need to swap playerNames, but does this mean I have to convert them to int or can they be swapped as a string (considering it is only changing their index).. – sethFrias Feb 22 '19 at 04:03
  • You don't have to worry with `std::swap` when swapping strings. You may want to read this: https://stackoverflow.com/questions/25286544/how-does-the-standard-library-implement-stdswap – Abhyudaya Sharma Feb 22 '19 at 04:10