查找阵列最小值 [英] Find min value in array
问题描述
我有两个数组:
int playerSums[9] = { };
string playerNames[9] = { };
我试图获取数组在最小值 playerSums
,并在数组索引此值
下面是我到目前为止已经试过:
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;
}
如何找到并显示数组中的最小值 playerSums
例如,如果的只有3名球员的都打,也就是说,只有3要素该阵列填充(和元件的其余部分是等于零)?
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.
推荐答案
您可以使用标准的算法的std :: min_element
在头&LT宣布;算法&GT;
,要找到元素WITN最小总和。例如:
You can use standard algorithm std::min_element
declared in header <algorithm>
that to find the element witn minimum sum. For example
#include <algorithm>
int *min = std::min_element( playerSums, playerSums + 3 );
std::cout << playerNames[min - playerSums]
<< " had the lowest values and got the sum " << *min
<< std::endl;
同样可以使用标准功能写入的std ::开始
,的std ::结束
和的std ::距离
在头部声明&LT;&迭代器GT;
#include <algorithm>
#include <iterator>
int *min = std::min_element( std::begin( playerSums ), std::end( playerSums ) );
std::cout << playerNames[ std::distance( playerSums, min )]
<< " had the lowest values and got the sum " << *min
<< std::endl;
除了使用算法,你可以写类似的算法自己的函数。例如:
Instead of using the algorithm you could write your own function similar to the algorithm. For example
size_t min_sum( int playerSums[], size_t n )
{
size_t min = 0;
for ( size_t i = 1; i < n; i++ )
{
if ( playerSums[min] < playerSums[i] ) min = i;
}
return min;
}
size_t min = min_sum( playerSums, sizeof( playerSums ) / sizeof( *playerSums ) );
std::cout << playerNames[min]
<< " had the lowest values and got the sum " << playerSums[min]
<< std::endl;
如果你需要跳过等于零数组的元素则函数将看起来像
If you need to skip elements of the array that equal to zero then the function will look like
size_t min_sum( int playerSums[], size_t n )
{
size_t min = 0;
while ( min < n && playerSums[i] == 0 ) ++min;
for ( size_t i = min; i < n; i++ )
{
if ( playerSums[min] < playerSums[i] ) min = i;
}
return min;
}
size_t min = min_sum( playerSums, sizeof( playerSums ) / sizeof( *playerSums ) );
if ( min != sizeof( playerSums ) / sizeof( *playerSums ) )
{
std::cout << playerNames[min]
<< " had the lowest values and got the sum " << playerSums[min]
<< std::endl;
}
这篇关于查找阵列最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!