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

标签 c++ arrays multidimensional-array

我将如何声明用户提供的大小为 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/

相关文章:

php - 如何用多维数组实现像excel小计函数这样的方法?

c++ - 有没有办法在 VS2012 中编写 make_unique() ?

php - 将多维数组拆分为单个数组 :PHP

php - 代码点火器 : create multidimensional array of result

php - 如何使用 For 循环将数组的数据插入不同的行

javascript - 使用 JavaScript 从多维数组创建 HTML

c - 如何通过环绕将 4 字节数组移位所有 32 位?

c++ - 正确使用原子

c++ - Qt - 如何在 QVBoxLayout 中放置具有左右边距的 QTextEdit?

c++ - 当文件存在时,最新检查声明构建输入 "is missing"