查找数组中的最小值

时间:2015-10-19 23:43:54

标签: c++

所以我遇到了一些问题。我必须创建一个函数,它将在数组中找到最小的数字。我知道一种方法,使用过量的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;
}

5 个答案:

答案 0 :(得分:3)

如果您可以更改函数签名并包含指定常规限制的头文件,则可以执行以下操作,一次性读取数组:

#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;
}

答案 1 :(得分:3)

template<size_t N>
int findLowest(int (&ar)[N])
{
    return *std::min_element(std::begin(ar), std::end(ar));
}

请注意模板的使用,以确保我们从调用者那里获取大小信息。

答案 2 :(得分: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;
}

答案 3 :(得分:0)

为什么不使用标准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

答案 4 :(得分:0)

#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;
}
相关问题