I’m working on a program that allows the user to input some names and integers for a soccer game, i.e. you input the player’s name, jersey number, & points scored and couts it all at the end. How would I go around to find the player’s name who scored the most points and cout that? I am using a struct for the players so it’s all in one instead of having individual ones for player 1 and 2 and so on.
This is my incomplete code below:
void showHighest(Player p[], int size)
{
int high = 0;
for (int counter = 0; counter < size; counter++)
{
if (high < p[counter].points)
{
high = p[counter].points;
}
if (p[counter].points )
{
}
}
cout << "The player with the most points was: " << p[high].name << "with " << high << "amount of points." << endl;
}
>Solution :
You need to track the index of the highest player in the array, not just the highest points. In your cout statement, you are using the highest points as if it were an index, which it is not.
Try this instead:
void showHighest(Player p[], int size)
{
int highest_points = 0;
int highest_index = -1;
for (int counter = 0; counter < size; ++counter)
{
if (highest_points < p[counter].points)
{
highest_index = counter;
highest_points = p[counter].points;
}
}
if (highest_index != -1)
cout << "The player with the most points was: " << p[highest_index].name << " with " << highest_points << " amount of points." << endl;
}
Alternatively:
void showHighest(Player p[], int size)
{
if (size < 1) return;
int highest_points = p[0].points;
int highest_index = 0;
for (int counter = 1; counter < size; ++counter)
{
if (highest_points < p[counter].points)
{
highest_index = counter;
highest_points = p[counter].points;
}
}
cout << "The player with the most points was: " << p[highest_index].name << " with " << highest_points << " amount of points." << endl;
}
Alternatively, you can use the standard std::max_element() algorithm to find the player with the highest points without using a manual loop, eg:
#include <algorithm>
void showHighest(Player p[], int size)
{
if (size < 1) return;
auto p_end = p + size;
auto it = std::max_element(p, p_end,
[](const Player &a, const Player &b){
return a.points < b.points;
}
);
cout << "The player with the most points was: " << it->name << " with " << it->points << " amount of points." << endl;
}