我将如何声明用户提供的大小为 n × n 的二维数组?
例如,为什么会这样:
int n;
cin >> n;
int *array = new int[n];
//no errors
但这不会:
int n;
cin >> n;
int *array = new int[n][n];
// these errors:
//error: array size in new-expression must be constant
//error: the value of 'n' is not usable in a constant expression
//note: 'int n' is not const
是否可以使用行和列大小为 n 的二维数组,还是必须使用 vector ?
谢谢!
最佳答案
用 vector 来做,像这样:
int n;
cin >> n;
auto matrix = std::vector<std::vector<int>>(n, std::vector<int>(n));
https://wandbox.org/permlink/zsOiUTvCbxAGmK6d
还有一个
std::valarray
template这与 std::vector
的功能类似,但具有有趣的额外功能,这在矩阵的情况下很有用。
关于c++ - 如何制作用户指定值的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46987459/