I have two arrays:
int playerSums[9] = { };
string playerNames[9] = { };
I am trying to get the smallest value in the array playerSums
and also the array index of this value.
Here's what I've tried so far:
if (playerNames[index] == "End" || playerNames[index] == "end") {
int lowestValue = playerSums[0];
for (i = 1; i < sizeof(playerSums) / sizeof(playerSums[0]); i++) {
if (playerSums[i] < lowestValue || lowestValue != 0)
lowestValue = playerSums[i];
}
cout << index[playerNames] << " had the lowest values and got the sum ";
cout << lowestValue << endl;
}
How do I find and display the smallest value in the array playerSums
if for example only 3 players are playing, i.e. only 3 elements of the array are populated (and the rest of the elements are equal to zero)?
I need the index to display the name of the player who got the smallest value.
As usual the simplest solution is to use the standard library, e.g.
Now you can get the min value by dereferencing the iterator
it
:If you only want to iterate over the first 3 elements in the array then you can do something like this instead:
Note: prefer
std::next
instead of plain pointer arithmetics (e.g.playerSums + 3
) as it is more generic (works on all iterator types).You know the index of the element you assign to
lowestValue
when you change that variable's value, so just save that index in a variable (say,index
), so that when you are doneindex
has the index of the last value assigned.You can use standard algorithm
std::min_element
declared in header<algorithm>
that to find the element witn minimum sum. For exampleThe same can be written using standard functions
std::begin
,std::end
andstd::distance
declared in header<iterator>
Instead of using the algorithm you could write your own function similar to the algorithm. For example
If you need to skip elements of the array that equal to zero then the function will look like
The same way that you are storing the lowest value in
lowestValue
, store the index in a variable, let's say,lowestValueIndex
. Also, remove the outer if and move it inside the for loop:this way, you will make sure that only the players who are playing will be processed. Also, you won't need to check if the lowest value is zero anymore. So the code will look like:
Just as a note, use an standard array that can grow to simplify this (like a
vector
):First adjust your for loop condition. I'm not sure if you defined i before so maybe you forgot that. Second the stop condition i < sizeof(palyerSums) is sufficient. Also you only need to store the index of the lowest playerSums in the array. The if condition also has something too much. If the lowestValue is not zero you will always change that value, that doesn't seem right unless the lowestValue is exactly zero.
Let me know if that works