我有一个结构数组,我需要从中检索数据。该数组包含名称和分数。
对于一个函数,我必须输出最高分和相关名称。如果有多种情况,我必须输出所有名称。
我不能使用向量或列表。(否则我会)我只想在同一步骤中执行这两个操作。
这就是我的处理方式:
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 循环。除非有人对更有效的方法提出建议。我认为对数据进行排序是不必要的。另外,如果已排序,如何确定一个步骤中是否有多个“highScore”案例。