以升序打印数组意味着降序

时间:2019-02-22 03:40:49

标签: c++

我正在尝试打印一个球员及其分数,从最高分到最低分。我可以使它下降,但它与正确的玩家名称无关。

使用以下代码:

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

我正在接收类似这样的输出

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

1 个答案:

答案 0 :(得分:1)

if语句中使用它:

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

交换分数时,您没有交换相应的playerNames。另外,如果您使用std::swap,则可读性更高。