* max_element用于查找范围内的最大值

时间:2020-08-30 13:37:28

标签: c++ arrays

是否存在* max_element的替代方法,用于在给定范围内查找数组中最大元素的值。我想同时避免循环和STL。

1 个答案:

答案 0 :(得分:0)

如果要避免循环或任何STL函数,可以使用递归方法。

大致草拟的代码如下所示

#include<iostream>
using std::cout;

int maxInt;
int maxRecur(int* arr, int length)
{
    if (length == 0)
        return maxInt;
    else
        if (maxInt < *arr)
            maxInt = *arr;
    maxRecur(arr+1, length-1);
}

int main()
{
    int arr[5] = { 1,4,9,3,2 };
    cout << maxRecur(arr, sizeof(arr) / sizeof(arr[0]));
}