Tuesday, 1 July 2008

Dynamic Allocation of Multidimensional Array

I suddenly found that actually the method of dynamic allocation of one-dimensional array is easy, just need a new operation of dynamic allocation of array, but for multi-dimensional array (e.g. matrix, tensor), you CAN'T just use one new operation.

Solutions:

(1) Pre-define a template class which deal with array

#using a standard container to calling
new [].

#include
#include
#include
#include

template <>
struct vector2d
{
vector2d(std::size_t n = 0) : m_Order(n), data( n * n ) {}
void set_Order(std::size_t n) { data.resize(n * (m_Order = n)); }

T *operator[](std::size_t off)
{
return &(data[off * m_Order]);
}
T const *operator[](std::size_t off) const
{
return &(data[off * m_Order]);
}

private:

std::size_t m_Order;
std::vector<> data;
};


int main()
{
using namespace std;

vector2d<> a(10);
int i, j;

for (i = 0; i < j =" 0;" i =" 0;" j =" 0;" style="font-weight: bold;">

(2) Use STL vector class, like std::vector, or std::valarray (recommanded!)


Two / Three / Multi Dimensioned arrays using vector:

A two dimensional array is a vector of vectors. The vector contructor can initialize the length of the array and set the initial value.

Example of a vector of vectors to represent a two dimensional array:
#include 
#include

using namespace std;

main()
{
// Declare size of two dimensional array and initialize.
vector<> > vI2Matrix(3, vector(2,0));

vI2Matrix[0][0] = 0;
vI2Matrix[0][1] = 1;
vI2Matrix[1][0] = 10;
vI2Matrix[1][1] = 11;
vI2Matrix[2][0] = 20;
vI2Matrix[2][1] = 21;

cout << "Loop by index:" << ii="0;" jj="0;">

A three dimensional vector would be declared as:


#include 
#include

using namespace std;

main()
{
// Vector length of 3 initialized to 0
vector vI1Matrix(3,0);

// Vector length of 4 initialized to hold another
// vector vI1Matrix which has been initialized to 0
vector<> > vI2Matrix(4, vI1Matrix);

// Vector of length 5 containing two dimensional vectors
vector<> > > vI3Matrix(5, vI2Matrix);

...

or declare all in one statement:

#include
#include

using namespace std;

main()
{
vector<> > > vI3Matrix(2, vector<> > (3, vector(4,0)) );

for(int kk=0; kk<4; jj="0;" ii="0;">

Source above (http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html)

(3) define a one-dimensional array of pointers, each points to a one-dimensional array, so that's two dimensional!

(4) convert you problem of multidimensional array to one-dimensional, and remember the way you put them to one-dimensional, then you may do whatever using new operation!

Anyway, multidimensional array is actually one-dimensional array, the ONLY difference is they are put in different format!

No comments: