递归函数,用于查找 2 个整数之间的最大值
Recursive Function to find Max value between 2 integers
我正在尝试创建一个递归函数,该函数在低整数和高整数之间的数组中查找最大数字。
我已经尝试过这个函数,它有助于递归地找到数组中的最大元素。我只是在如何添加到函数中遇到麻烦,该函数接受低整数和高整数以找到这 2 之间的最大值。
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现在定义了一个函数std::size,可以返回数组的大小。
#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;
}
如果您没有 C++17,您会考虑使用列表吗?
#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()));
}
findMaxBetwen
可以作为函数模板实现:
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
}
在 cpp 首选项中了解有关函数模板的详细信息
相关文章:
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 禁止指针和整数之间的比较C++
- Qt 错误 iso c++ 禁止指针和整数之间的比较 -permissive
- 递归函数,用于查找 2 个整数之间的最大值
- 如何包含整数之间的空格作为输出
- 在两个整数之间交换最右边的N位
- 打印出两个整数之间的偶数
- 定义整数之间的特殊划分
- 如何修复C++中的"指针和整数之间的比较"错误?
- 如何计算两个负整数 c++ 之间的总和
- 字符串和整数之间的模板冲突
- 如何在正整数和负整数之间进行匹配
- 将 OR 放入 if 语句会导致 ISO C++禁止指针和整数之间的比较(f 允许)
- C++无符号整数和无符号长整形整数之间的区别
- 错误(ISO C++禁止指针和整数之间的比较)[-fperemissive]
- ISO C++禁止指针和整数之间的比较
- 解释为 4 个字节的两个整数之间的计算范数
- 有符号整数和无符号整数之间的转换
- C 帮助(ISO C 禁止指针和整数之间的比较.)
- 高效实现 64 位和 32 位无符号整数之间的双向映射