二维数组 - 表达式必须有常量值错误

2-D Array - Expression must have a constant value error

我正在尝试 Latin Square Daily Challenge on Reddit,我想使用一个在 运行 时间内分配大小的数组,方法是使用以下代码:

int n;
cout << "Please enter the size of the Latin Square: ";
cin >> n;
int latinsquare[n][n];

这适用于在线编译器,但不适用于 Visual Studio 17. 有没有办法在 Microsoft C++ 编译器中执行此操作?

VLA is not a part of 标准。如果你想使用它们,你需要编译器扩展。

但是你可以

  • 通过 newdelete 运算符动态创建它

  • 使用std::vector

这是因为可变长度数组在 C++ 中是非标准的 (why?)。您可以使用 new 分配 latinsquare,但在 C++ 中,一种惯用的方法是使用向量的向量:

std::vector<std::vector<int>> latinsquare(n, std::vector<int>(n, 0));