c++ - 为什么在我的主函数中声明一个整数后我的整数数组中有错误?
问题描述
我正在尝试一些代码,这些代码基于查找所有可能的组合,这些组合加起来是在主函数中声明的整数值。然而,问题是当我调用函数“findCombinations(n);”时,它在“int arr[n];”处给出错误。这是唯一有错误阻止我运行程序的行。如果您知道解决方案,请告诉我。
#include <iostream>
using namespace std;
void findCombinationsUtil(int arr[], int index,
int num, int reducedNum)
{
// Base condition
if (reducedNum < 0)
return;
// If combination is found, print it
if (reducedNum == 0)
{
for (int i = 0; i < index; i++)
cout << arr[i] << " ";
cout << endl;
return;
}
// Find the previous number stored in arr[]
// It helps in maintaining increasing order
int prev = (index == 0) ? 1 : arr[index - 1];
// note loop starts from previous number
// i.e. at array location index - 1
for (int k = prev; k <= num; k++)
{
// next element of array is k
arr[index] = k;
// call recursively with reduced number
findCombinationsUtil(arr, index + 1, num,
reducedNum - k);
}
}
void findCombinations(int n)
{
// array to store the combinations
// It can contain max n elements
int arr[n];
//find all combinations
findCombinationsUtil(arr, 0, n, n);
}
int main()
{
int n = 10;
findCombinations(n);
return 0;
}
解决方案
在标准 C++ 中,必须在编译时知道 C 样式的数组维度。
您可以n
像这样作为编译时函数参数:
template<int n>
void findCombinations()
{
// array to store the combinations
// It can contain max n elements
int arr[n];
//find all combinations
findCombinationsUtil(arr, 0, n, n);
}
int main()
{
const int n = 10;
findCombinations<n>();
return 0;
}
推荐阅读
- sql - 将 Table1 的所有记录复制到 Table2 中,并将单独的数据插入到 Table2 中
- java - 为什么在使用 SimpleDateFormat 解析字符串中的日期时会得到错误的结果?(爪哇)
- java - 使用流将集合拆分为在地图中分组的多个集合
- javascript - 同一组数据的两个图表 - Chart.js
- python - 如何按周聚合 Pandas 中的多级索引,以星期为列?
- sql - 仅在基础数据更改时重新计算的 SQL 计算表
- angular - 反应形式的角度 matDatepicker
- c - C中的Prim算法产生不正确的输出
- powershell - 从与 powershell 脚本相同的目录安装 .MSI 文件,而不设置静态文件路径
- javac - Javac 找不到源代码 - windows