I have an array of structs that I need to retrive data from. The array holds names and scores.
For one function I have to output the highest score and the name associated. If there are multiple cases I must output all names.
I CANNOT USE VECTORS or LISTS. (else I would) I just want to perform both actions in the same step.
This is how I’m handling it:
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
I would like to condense this to one for loop. Unless someone has a suggestion for an even more efficient method. I would think sorting the data would be unnecessary. Plus if it’s sorted, how could determine if there were more than one “highScore” case in one step.
One solution would be to record the names of the players as you’re searching for the high score. If it’s equal to the current high score, then append an additional name to your “collection of names string”, and if it’s higher, blank out the names, and record the new high score and new name as well. I’d implement the printout of names as an
ostringstreamto ensure you don’t run over a buffer. Then when you’re done, print out your set of names.