您可以使用標準算法std::min_element
在頭<algorithm>
宣稱找到元素WITN最小總和。例如
#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;
}
請解釋您當前的代碼有錯誤。當你在這裏,解釋內部'if'語句背後的邏輯:) – 2014-10-02 17:40:24
你見過http://stackoverflow.com/questions/23871658/cs-min-element-not-working-for-array? – matsjoyce 2014-10-02 17:41:31
'std :: vector'讓生活變得如此簡單。 – 2014-10-02 17:42:52