gpt4 book ai didi

c++ - 如何制作用户指定值的二维数组?

转载 作者:行者123 更新时间:2023-11-30 02:22:43 25 4
gpt4 key购买 nike

我将如何声明用户提供的大小为 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 的功能类似,但具有有趣的额外功能,这在矩阵的情况下很有用。

https://wandbox.org/permlink/9Vq141QpEWcWoUxM

关于c++ - 如何制作用户指定值的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46987459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com