class, 3D-Array, return style
Sep 19, 2010 at 4:36pm UTC
Dear all,
I have class names Tensor, which contains a 3 dimensional array. The access to that array can be done like in Fortran by:
1 2 3
Tensor<double > density;
[...]
density(z,y,x) = do something;
But I would like to have also an C/C++ access-style:
1 2 3
Tensor<double > density;
[...]
density[z][y][x] = do something;
To enable to make things like that:
1 2 3 4 5
Tensor<double > density;
[...]
double **tmp;
tmp = density[25];
The class definition:
1 2 3 4 5 6 7 8 9 10 11 12
template <class T> class Tensor : protected DimS{
protected :
T ***data;
public :
T& operator ()(int z, int y, int x) {return data[z][y][x];};
T operator ()(int z, int y, int x) const {return data[z][y][x];};
[...]
};
The 3D-array data is allocated by:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
template <class T> T ***allocate_3D(itype nz, itype offz,
itype ny, itype offy,
itype nx, itype offx
)
{
T ***field;
size_t NZ = (size_t)(nz + 2*offz);
size_t NY = (size_t)(ny + 2*offy);
size_t NX = (size_t)(nx + 2*offx);
field = (T ***) calloc (NZ, sizeof (T **)) + offz;
if ( NULL == field ){ _error("Could not allocate the field" ); }
field[-offz] = (T **) calloc (NZ*NY, sizeof (T *)) + offy;
if ( NULL == field[-offz] ){free(field); _error("Could not allocate the field" ); }
field[-offz][-offy] = (T *) calloc (NZ*NY*NX, sizeof (T))
+ offx;
if ( NULL == field[-offz][-offy] ){
free(field[-offz]);
free(field);
_error("Could not allocate the field" );
}
for (itype i=1-offz ; i < nz+offz ; i++)
field[i] = field[i-1] + NY;
for (itype i=1-offz; i < nz+offz ; i++)
field[i][-offy] = field[i-1][-offy] + NY*NX;
for (itype i=-offz ; i < nz+offz ; i++)
for (itype j=1-offy ; j < ny+offy ; j++)
field[i][j] = field[i][j-1] + NX;
return field;
}
Thanks a lot for help!
Topic archived. No new replies allowed.