数组类型 int[n][n] 不可赋值,因为表达式必须具有常量值

array type int[n][n] is not assignable, because of expression must have a constant value

本文关键字:表达式 常量 赋值 int 类型 数组 因为      更新时间:2023-10-16

我得到错误:表达式必须在第 4 行(int cost[n][n](上有一个常量值,并且基于它的进一步错误,即"数组类型 int[n][n] 不可分配"。 如何修复它们?

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];
}

在 c++ 中创建动态 n*n 大小的 2d 数组的标准方法是这样的

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

见向量向量,保留