问题描述
我还是不太了解矩阵和其他多维数组在C和C +中的表示方式以及如何动态分配。以下代码段:
int main()
{
int n;
cin>> n;
int a [n] [n];
...
}
如果我理解正确,乘以n的整数矩阵。
可以使用a [i] [j]访问矩阵的第(i,j)元素。编译器
自动将其转换为对实际分配的一个
维数组的第(n * i + j)个元素的访问。
假设现在我想在堆上分配n乘n矩阵a,而不是堆栈的
。我可以这样做:
int main()
{
int n;
cin>> n;
int ** a;
a = new int * [n];
for(int i = 0; i ...
}
现在我可以访问)元素作为a [i] [j]。然而,这不完全是
相当于上面的情况,因为我实际上必须为n * n int,
加n指针为int分配空间。此外,访问a [i] [j]现在需要两次访问内存,而
只有一次。另一方面,避免索引计算n * i + j。假设现在我对m个矩阵中的n个感兴趣,其中m很小,例如m = 2。
使用行指针数组,然后浪费33%的空间。有没有任何方式的
避免?
我当然可以分配一维数组和索引算法自己,
但这个对我来说似乎不是最好的解决方案。
任何信息将不胜感激。
您可以创建一个为您执行索引数学的类,如果这是您不喜欢的地方。
class Matrix
{
public:
Matrix(int iRows,int iCols)
:mRows(iRows),mCols(iCols),m * mCols]){}
〜Matrix(){delete [] m; }
int& element(int iRow,int iCol){return m [iRow * mCols + iCol]; }
int mRows,mCols,* m;
};
There is something I still don't quite understand about the way matrices and other multidimensional arrays are represented in C and C+ and how to allocate them dynamically.
Consider the following code segment:
int main()
{
int n;
cin >> n;
int a[n][n];
...
}
If I understand correctly, this allocates an n by n matrix of integers on the stack.The (i,j)-th element of the matrix can be accessed using a[i][j]. The compilerautomatically converts this into an access into the (n*i+j)-th element of a onedimensional array actually allocated.
Suppose now that I would like to allocate the n by n matrix a on the heap, insteadof the stack. I can then do the following:
int main()
{
int n;
cin >> n;
int** a;
a = new int*[n];
for (int i=0;i<n;i++) a[i] = new int[n];
...
}
I can now access the (i,j)-th element again as a[i][j]. However, this is not exactlyequivalent to the situation above as I actually had to allocate space for n*n int's,plus n pointers to int. Also, accessing a[i][j] now entails two accesses to memory insteadof just one. On the other hand, the index computation n*i+j is avoided.
Suppose now that I am interested in n by m matrices where m is small, e.g., m=2.Using the array of row pointers then wastes 33% of the space. Is there any way ofavoiding that?
I can of course allocate a one-dimensional array and do the index arithmetic myself,but this does not seem to be the best solution to me.
Any information would be appreciated!
You could create a class that did the index math for you, if that's where you're not liking things.
class Matrix
{
public:
Matrix(int iRows, int iCols)
: mRows(iRows), mCols(iCols), m(new int[mRows*mCols]) { }
~Matrix() { delete [] m; }
int &element(int iRow, int iCol) { return m[iRow * mCols + iCol]; }
int mRows, mCols, *m;
};
这篇关于矩阵与数组在C ++中的数组及其动态分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!