Help with Array template

H

hrmadhu

Hi,
I am trying to write a template for an array which I can use to
create multi-dimensional matrices as

// A 10x10 matrix with each element initialized to 0
Array< Array<int> > Matrix (10,0);

// A 5x5x5 3-dimensional matrix with each element initialized to 1
Array< Array <Array<int> > > Matrix3D (5,1);

// A 15x15x15x15 4-dimensional matrix with each element initialized to
10
Array< Array< Array< Array<int> > > > Matrix4D(15,10);

The code for the array class is as follows:

template < class T> class Array
{
private:
T* _data;
public:
Array(int Size, T Initializer)
{
int i;
_data= new T[Size];
for(i=0;i<Size;i++)
{
_data=Initializer;
/****************************************************
/***** OR SHOULD I USE
_data=T(Initializer);
/****************************************************/
}
}
};

Now if I try and declare a matrix as

Array< Array<int> > Matrix (10, 10 );

the compiler cribs as it expects an initializer of type Array<int> for
the Initializer when it does
_data=T(Initializer);

Can someone please help me out ? how do I write a template for an
Array such that I can easily extend it to multidimensions
thanks a lot in advance.

Regards,
Madhu
 
B

Buster

Now if I try and declare a matrix as

Array< Array<int> > Matrix (10, 10 );

the compiler cribs as it expects an initializer of type Array<int> for
the Initializer when it does
_data=T(Initializer);



Try

Array <Array <int> > Matrix (10, Array <int> (10));

Regards,
Buster.
 
?

=?iso-8859-1?Q?Juli=E1n?= Albo

hrmadhu escribió:
I am trying to write a template for an array which I can use to
create multi-dimensional matrices as

I modified your code giving this:

#include <memory>

template <class T> class Array
{
private:
T * _data;
int s;
public:
Array(int Size, const T & Initializer)
{
s= Size;
int i;
_data= std::allocator <T> ().allocate (Size);
for(i=0;i<Size;i++)
{
new (& _data ) T (Initializer);
}
}
Array (const Array & a)
{
_data= std::allocator <T> ().allocate (a.s);
for (int i= 0; i < a.s; ++i)
{
new (& _data ) T (a._data );
}
}
~Array ()
{
for (int i= 0; i < s; ++i)
{
_data .~T ();
}
std::allocator <T> ().deallocate (_data, s);
}
};

int main ()
{
// 10x10 matrix with values initialized to 1.
Array <Array <int> >
Matrix2D (10, Array <int> (10, 1) );
// 10x10x10 matrix with values initialized to 1.
Array <Array <Array <int> > >
Matrix3D (10, Array <Array <int> > (10, Array <int> (10, 1) ) );
}

Warning! I don't tested it more than compiling and executing the result.

You probably need to add an assignment operator to Array, or to forbid
the assignment.

Regards.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,373
Latest member
Desiree036

Latest Threads

Top