我有两个数组:
int playerSums[9] = { };
string playerNames[9] = { };
我试图获取数组中的最小值playerSums
以及该值的数组索引。
到目前为止,这是我尝试过的方法:
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个元素(其余元素等于零),如何找到并显示阵列中的最小值?
我需要索引来显示获得最小价值的玩家的姓名。
您可以使用标std::min_element
头<algorithm>
中声明的标准算法来查找具有最小和的元素。例如
#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::begin
,std::end
并std::distance
在标头中声明<iterator>
#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;
除了使用该算法外,您还可以编写类似于该算法的自己的函数。例如
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;
如果您需要跳过等于零的数组元素,则该函数将如下所示
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句