PDA

View Full Version : مبتدی: مشکل در کلاس ارایه سه بعدی :((



H_G_G_I
شنبه 25 آذر 1391, 12:31 عصر
سلام دوستان من یه کلاس برا ارایه سه بعدی نوشتم ! البته فعلا کامل نیست . یکمی هم مشکل داره !:ناراحت:

الان اولین مشکلم اینه که من اگه اریه رو به صورت پشت سر هم در نظر بگیرم
یعنی اینطوری ::

int* arr = new int[size_x * size_y *size_z];


بعد اگه بخوام به عنصر 2,3,4 دسترسی داشته باشم باید این طوری بنویسم ؟

//_x = 2
//_y = 3
//_z = 4
arr[_z * size_y * size_x + _y * size_x + X ];

اینو درستشو بگید. :گیج:

حالا بجاش int*** در نظر گرفتم. ولی نمی دونم مخرب کلاس رو درست نوشتم یا نه . :متفکر: :متفکر:
درسته؟:متفکر:

اینم کد ::

#define MULTIALLOC

template <typename T> class Array3D
{
public:
Array3D(size_t _x, size_t _y, size_t _z);
~Array3D();
void setVal(size_t _x, size_t _y, size_t _z, T _val);
T getVal(size_t _x, size_t _y, size_t _z);

private:

#ifdef MULTIALLOC
T*** arr;
#else
T* arr;
#endif;

size_t size_x, size_y, size_z;
};

template <typename T>
Array3D<T>::Array3D( size_t _x, size_t _y, size_t _z )
{
size_x = _x;
size_y = _y;
size_z = _z;

#ifdef MULTIALLOC
arr = new T**[_x];
for(int i = 0; i< _x; i++)
{
arr[i] = new T*[_y];
for(int j = 0; j< _y; j++)
{
arr[i][j] = new T[_z];
}
}
#else
arr = new T[_x*_y*_z];
#endif;
}

template <typename T>
T Array3D<T>::getVal( size_t _x, size_t _y, size_t _z )
{
#ifdef _DEBUG
if(_x >= size_x )
_x %= size_x;
if(_y >= size_y)
_y %= size_y;
if(_z >= size_z)
_z %= size_z;
#endif

#ifdef MULTIALLOC
return arr[_x][_y][_z];
#else
return arr[_z * size_y * size_x + _y * size_x + X ]; //?????????????????????? :((
#endif;

}

template <typename T>
void Array3D<T>::setVal( size_t _x, size_t _y, size_t _z, T _val )
{
#ifdef _DEBUG
if(_x >= size_x )
_x %= size_x;
if(_y >= size_y)
_y %= size_y;
if(_z >= size_z)
_z %= size_z;
#endif

#ifdef MULTIALLOC
arr[_x][_y][_z] = _val;
#else
return arr[_z * size_y * size_x + _y * size_x + X ]; //??????????????? :((
#endif;
}

template <typename T>
Array3D<T>::~Array3D()
{
#ifdef MULTIALLOC

//?????????????? :-?
// for(int i = size_x-1; i >= 0; i--)
// {
// for(int j = size_y-1; j >= 0; j--)
// {
// delete[] arr[i][j];
// }
// delete[] arr[i];
// }
// delete[] arr;

//?????????????????? :D
for(int i = 0; i< size_x; i++)
{
for(int j = 0; j< size_y; j++)
{
delete[] arr[i][j];
}
delete[] arr[i];
}
delete[] arr;

#else
delete[] arr;
#endif

}

H_G_G_I
یک شنبه 26 آذر 1391, 10:05 صبح
:گریه:
:گریه:
:گریه: