c++ - 查找数组中的最大值 C++

标签 c++ arrays function

<分区>

所以这就是我想要做的 - 编写一个包含 50 个值的数组的程序,获取数组中的最大数字并将其打印出来。不过我碰壁了。我很确定我对函数中的返回感到非常困惑,例如,为什么在 findSmall 和 finBig 函数的 for 循环中索引“未定义”?

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int findSmallest(int array[], int size, int index)
{
    int index_of_smallest_value = index;
    for (int i = index + 1; i < size; i++)
    {
        if (array[i] < array[index_of_smallest_value])
        {
            index_of_smallest_value = i;
        }
    }
    return index_of_smallest_value;
}

int findBiggest(int array[], int size, int index)
{
    int index_of_biggest_value = index;
    for (int i = index + 1; i < size; i++)
    {
        if (array[i] > array[index_of_biggest_value])
        {
            index_of_biggest_value = i;
        }
    }
    return index_of_biggest_value;
}

int findSmall(int array[], int size)
{
    int index = 0;
    for (int i = 0; i < size; i++)
    {
        index = findSmallest(array, size, i);
        //cout << index << endl;
    }
    return index;
}

int findBig(int array[], int size)
{
    int index = 0;
    for (int i = 0; i < size; i++)
    {
        index = findBiggest(array, size, i);
        //cout << index << endl;
    }
    return index;
}

int main()
{
    int array[50];
    srand(time(NULL));

    for (int i = 0; i < 50; i++)
        array[i] = rand() % 100;

    cout << "The smallest digit is " << findSmall(array, 50) << endl;
    cout << "The biggest digit is " << findBig(array, 50);
    cin.get();
}

我已经编辑了上面的代码,但是我总是从 findSmall 和 finBig 函数返回 49。

最佳答案

你可以用 C++/STL 的方式来做。这不仅适用于数组,也适用于其他 STL 容器。

#include <iterator>
#include <algorithm>

int minelem = *std::min_element(begin(array), end(array));
int maxelem = *std::max_element(begin(array), end(array));

此代码在数组上循环两次。出于性能原因,您可能会考虑合并循环。或者在 C++11 中你甚至可以

auto result = std::minmax_element(begin(array), end(array));

关于c++ - 查找数组中的最大值 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24754944/

相关文章:

javascript - 为什么这段代码在 javascript 中运行?对象内部函数

javascript - 如何在保持相同 API 的同时将此 JavaScript 包装在立即调用的函数表达式 (IIFE) 中?

C++:如何随机生成不同数字的序列?

c++ - 编译好的文件放到文件夹后无法运行程序

c++ - "No matching function for call to"模板 C++

Python IndexError - 需要帮助排序键和值

javascript - 在 JavaScript 中设置数组

c - 将数组作为参数传递并交换数据 - 意外数据

c++ - 是否可以在主应用程序中使用在 DLL 中创建的 CPropertyPage?

c++ - 作为友元的运算符重载