C++ 用于查找2个整数之间的最大值的递归函数

C++ 用于查找2个整数之间的最大值的递归函数,c++,recursion,C++,Recursion,我试图创建一个递归函数,在数组中查找介于低整数和高整数之间的最大数 我尝试过这个函数,它可以帮助递归地查找数组中的最大元素。我只是不知道如何将低整数和高整数添加到函数中,以找到这两个整数之间的最大值 int findMaxRec(int A[], int n) { // if n = 0 means whole array has been traversed if (n == 1) return A[0]; return max(A[n-1],

我试图创建一个递归函数,在数组中查找介于低整数和高整数之间的最大数

我尝试过这个函数,它可以帮助递归地查找数组中的最大元素。我只是不知道如何将低整数和高整数添加到函数中,以找到这两个整数之间的最大值

int findMaxRec(int A[], int n) 
{ 
    // if n = 0 means whole array has been traversed 
    if (n == 1) 
        return A[0]; 
    return max(A[n-1], findMaxRec(A, n-1)); 
} 
我们的目标是创建一个如下所示的函数:

int findMaxBetwen(int A[], int low, int high){
      //Here is where I need help integrating if lets say the array is A[] = 5,6,7,8
      // Call findMaxBetwen(A[], 5, 8) and the output gives 7 because that is the max between the 3 
      //integers.
}
更新:C++17现在定义了一个可以返回数组大小的函数

#include <iostream>
#include <iterator>

using namespace std;

int findMaxRec(const int[] A, const int &n)
{
  if (n <= 0) throw "error: array is empty...";
  if (n == 1) return A[0];
  return std::max(A[n - 1], findMaxRec(A, (n - 1)));
}

int findMaxRec(const int[] A)
{
  return findMaxRec(A, std::size(A));
}

const int& findMaxRec(const int &i)
{
  return i;
}

了解有关函数模板的更多信息,请访问

问题是什么?我不知道如何回答这个问题而不破坏您的所有乐趣提示:在您当前的函数中,它会导致在第一个元素处停止的原因是什么?从最后一个元素开始是什么原因?识别这两个变量,并将其替换为从高开始,在低停止。到目前为止,在我的驱动程序代码中,我仍然有点困惑。n表示为sizeofA/sizeofA[0],这给出了数组长度的大小。那么,我应该用低和高替换当前代码的n部分吗?什么驱动程序代码?你应该吗?我不知道,因为我不知道密码。当你尝试时会发生什么?
#include <algorithm>
#include <list>

int findMaxRec(const std::list<int> &L)
{
  if (L.size() == 0) throw "error: list is empty...";
  return (*std::max_element(L.begin(), L.end()));
}
template<typename T> int findMaxBetwen(const T &data, int low, int high)
{
  int i = findMaxRec(data);
  if (i <= low) return low;
  if (i >= high) return high;
  return i;
}

//....

int main(int argc, char** argv)
{
  std::list<int> a = {5, 6, 7, 8, 10};
  cout << findMaxBetween(a, 5, 8) << '\n'; // output is 8

  int b[5] = {5, 6, 7, 8, 10};
  cout << findMaxBetween(b, 5, 8) << '\n'; // output is 8

  int c = 7;
  cout << findMaxBetween(c, 5, 8) << '\n'; // output is 7
}