我该如何声明用户给出的大小为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的二维数组,或者你必须使用向量?
谢谢!
发布于 2017-10-28 15:54:29
用一个向量来做,就像这样:
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相似,但具有有趣的额外功能,这在矩阵的情况下可能很有用。
发布于 2017-10-28 16:10:21
要创建多维数组,您必须编写以下代码:
int n;
cin >> n;
int **array = new int*[n];
for (int i = 0; i < n; i++) {
array[i] = new int[n];
}别忘了删除它:
for (int i = 0; i < n; i++) {
delete[] array[i];
}
delete[] array;但是当前c++的最佳实践是永远不要在应用程序代码中分配或释放内存,这意味着您应该使用std::vector或其他容器类。
发布于 2017-10-28 23:21:21
可以在不使用向量的情况下创建一个二维数组,如下所示。这将适用于所有类型。
template <typename T>
T **Alloc2D( int nRows, int nCols)
{
T **array2D;
array2D = new T*[nRows];
for( int i = 0 ; i < nRows ; i++ )
array2D[i] = new T [nCols];
return array2D;
}
template <typename T>
void Free2D(T** dArray)
{
delete [] *dArray;
delete [] dArray;
}但是,问题是内存管理,因为它是一种原始的方法。
相反,我们可以使用可管理的向量,如
typedef vector<vector<int>> ARRAY2D;https://stackoverflow.com/questions/46987459
复制相似问题