-3

I got the error: expression must have a constant value on line 4(int cost[n][n]), and further errors base on it, which is "array type int[n][n] is not assignable" . How do I fix them?

 int optimalSearchTree(int keys[], int freq[],  int n)
    {
        /* Create an auxiliary 2D matrix to store results of subproblems */

        int cost[n][n];
        for (int i = 0; i < n; i++)
            cost[i][i] = freq[i];

        for (int L = 2; L <= n; L++)
        {
            // i is row number in cost[][]
            for (int i = 0; i <= n - L + 1; i++)
            {
                // Get column number j from row number i and chain length L
                int j = i + L - 1;
                cost[i][j] = INT_MAX;

                // Try making all keys in interval keys[i..j] as root
                for (int r = i; r <= j; r++)
                {
                    // c = cost when keys[r] becomes root of this subtree
                    int c = ((r > i) ? cost[i][r - 1] : 0) +
                        ((r < j) ? cost[r + 1][j] : 0) +
                        sum(freq, i, j);
                    if (c < cost[i][j])
                        cost[i][j] = c;
                }
            }
        }
        return cost[0][n - 1];
    }
Rio Chen
  • 1
  • 7

1 Answers1

-1

The standard way to create a dynamically n*n sized 2d array in c++ is like this

std::vector<std::vector<int> > cost(n,std::vector<int>(n));

see Vector of vectors, reserve

pm100
  • 48,078
  • 23
  • 82
  • 145
  • 2
    Though quite often it is not a good idea to represent matrix by vector of vectors, but that is a different story. – Slava Oct 11 '18 at 17:18
  • @Slava - please post an alternative then. I agree the vec of vec is probably not as fast are pure 2d array – pm100 Oct 11 '18 at 17:21
  • @pm100 A 1-D array or vector of elements of size n * n, together with operators or functions to correctly calculate the 1-D index from two 2-D indexes. –  Oct 11 '18 at 17:39
  • thats such a useful construct its surprising that there is nothing standard for it , maybe in boost? – pm100 Oct 11 '18 at 17:41
  • can somebody post another answer Slava? Neil B? – pm100 Oct 11 '18 at 17:42
  • i am only trying to help the OP. I googled for that and found matrix math libraries. If you know a good solution for the question why not post it. – pm100 Oct 11 '18 at 17:50