In C++ you can easily allocate one dimensional array like this:
T *array=new T[N];
And you can delete it with one statement too:
delete[] array;
The compiler will know the magic how to deallocate the correct number of bytes.
But why can’t you alloc 2-dimensional arrays like this?
T *array=new T[N,M];
Or even like this?
T *array=new T[N,M,L];
If you want a multidimensional you have to do it like this:
T **array=new T*[N];
for(int i=0;i<N;i++) array[i]=new T[M];
If you want a fast program that uses matrices (matrix operations, eigenvalue algorithms, etc…) you might want to utilize the cache too for top performance and this requires the data to be in the same place. Using vector<vector<T> > is the same situation. In C you can use variable length arrays on the stack, but you can’t allocate them on the heap (and stack space is quite limited), you can do variable length arrays in C++ too, but they won’t be present in C++0x.
The only workaround is quite hackish and error-phrone:
T *array=new T[N*M];
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
{
T[i*N+j]=...;
}
Your workaround of doing
T *array=new T[N*M];is the closest you can get to a true multi-dimensional array. Notice that to locate the elements in this array, you need the value ofM(I believe your example is wrong, it should beT[i*M+j]) which is known only at run-time.When you allocate a 2D array at compile-time, say
array[5][10], the value10is a constant, so the compiler simply generates code to computei*10+j. But if you didnew T[N,M], the expressioni*M+jdepends on the value ofMat the time the array was allocated. The compiler would need some way to store the value ofMalong with the actual array itself, and things are only going to get messy from here. I guess this is why they decided not to include such a feature in the language.As for your workaround, you can always make it less “hackish” by writing a wrapper class that overloads
operator (), so that you could do something likearray(i, j) = ....