[英]Finding the smallest value in an array
所以我遇到了一些麻煩。 我必須創建一個函數來查找數組中的最小數字。 我知道一種方法,使用大量的 if/else if,如果數組大小發生變化,這將沒有任何好處。 我知道使用 for 循環應該可以解決問題,但我不知道如何編寫它。 任何朝着正確方向的推動將不勝感激。
#include <iostream>
using namespace std;
int findLowest(int[]);
int main()
{
int AR[5] = {4, 87, 1, -3, 78};
cout << findLowest(AR);
return 0;
}
int findLowest(int AR[])
{
return lowest;
}
如果您可以更改函數簽名並包括指定一般限制的頭文件,則可以執行以下操作,該操作可以一次性讀取數組:
#include <climits>
...
/* assumes AR_size > 0 */
int findLowest(int AR[], int AR_size)
{
int lowest = INT_MAX;
for (i = 0; i < AR_size; ++i) {
lowest = (AR[i] < lowest) ? AR[i] : lowest;
}
return lowest;
}
template<size_t N>
int findLowest(int (&ar)[N])
{
return *std::min_element(std::begin(ar), std::end(ar));
}
請注意模板的用法,以確保我們從調用方獲得尺寸信息。
為什么不定義自己的函數來查找數組中最小的數字,為什么不使用標准的std::min_element
函數為您完成呢? 從數組創建一個std::vector
對象,然后讓min_element函數為您完成這項工作。
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>
#define ARRAY_SIZE 5
int main ( int argc, char **argv )
{
int ar [ ARRAY_SIZE ] = {4, 87, 1, -3, 78};
std::vector<int> arVector ( ar, ar + ARRAY_SIZE );
std::cout << *std::min_element ( arVector.begin ( ), arVector.end ( )) << std::endl;
return EXIT_SUCCESS;
}
輸出:
-3
#include <iostream>
#include <cassert>
using namespace std;
int findLowest(int ar[], const int& SIZE)
{
assert(("Error: the size of the array is zero. Make sure that ", SIZE > 0));
int lowest = ar[0];
for(int i=0; i<SIZE;i++)
{
if(lowest > ar[i])
lowest = ar[i];
}
return lowest;
}
int main()
{
const int SIZE(5);
int AR[5] = {11, 12, 10, 14, 15};
cout << findLowest(AR,SIZE);
return 0;
}
#include <iostream>
using namespace std;
int findLowest(int ar[])
{
int lowest = 1000000;
for(int i=0; i<5;i++)
{
if(lowest > ar[i])
lowest = ar[i];
}
return lowest;
}
int main()
{
int AR[5] = {4, 87, 1, -3, 78};
cout << findLowest(AR);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.