データを取得する必要のある構造体の配列があります。配列は名前とスコアを保持します。
1つの関数について、最高のスコアと関連付けられた名前を出力する必要があります。複数の場合がある場合は、すべての名前を出力する必要があります。
ベクトルやリストを使用できません。(そうでない場合)同じステップで両方のアクションを実行したいだけです。
これが私がそれを処理する方法です:
void highScorer ( player array[], int size )
{ // highScorer
int highScore = 0; //variable to hold the total score
// first loop determines highest score
for ( int i = 0; i < size; i++ ) {
if ( array[i].pointsScored > highScore ) {
highScore = array[i].pointsScored;
}
}
cout << "\nThe highest scoring player(s) were:\n";
// second loop finds players with scores matching highScore and prints their name(s)
for ( int i = 0; i < size; i++ ) {
// when a match is found, the players name is printed out
if ( array[i].pointsScored == highScore ) {
cout << array[i].playerName;
cout << ", scored ";
// conditional will output correct grammar
if ( array[i].pointsScored > 1 ) {
cout << array[i].pointsScored << " points!\n";
}
else {
cout << array[i].pointsScored << " point!\n";
}
}
}
cout << "\n"; // add new line for readability
return;
} // highScorer
これをforループに凝縮したいと思います。誰かがさらに効率的な方法の提案を持っていない限り。データの並べ替えは不要だと思います。さらに、ソートされている場合、1つのステップで複数の「highScore」ケースがあったかどうかをどのように判断できますか。