首页 > 解决方案 > 为什么在我的主函数中声明一个整数后我的整数数组中有错误?

问题描述

我正在尝试一些代码,这些代码基于查找所有可能的组合,这些组合加起来是在主函数中声明的整数值。然而,问题是当我调用函数“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++visual-studiovisual-c++

解决方案


在标准 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;
}

推荐阅读