Multi-dimensional dynamic array - performance
Hi everyone,
I am currently learning c++ (but having programmed in fortran 95 before, it is mostly a case of learning new syntax, and a few new concepts, in order to be familiar with the basics).
For the purposes of a large scientific code that I am preparing to write, I will need to create multi-dimensional arrays dynamically, since the array size in each dimension will be known only at run-time. I will need to create 3D, 6D and 7D arrays.
I have of course looked around a lot to find ways to do this, and have come up with the following (for a 3D array, but I can extend it to 6 and 7D easily):
Code:
#include <iostream>
using namespace std;
/* 3D ARRAY CLASS */
class array3d
{
public:
void allocate(int nx,int ny,int nz); // Allocate the array
double ***array; // The pointer to the array
};
void array3d::allocate(int nx,int ny,int nz) {
array = new double**[nx];
for(int i=0;i<nx;i++) {
array[i] = new double*[ny];
for(int j=0;j<ny;j++) {
array[i][j] = new double[nz];
}
}
}
/* MAIN PROGRAM */
int main() {
array3d image;
/* Allocate the array */
image.allocate(100,100,100);
/* Assign values to two elements as an example */
image.array[33][34][32]=0.6;
image.array[99][22][10]=0.8;
cout<<image.array[33][34][32]<<endl;
cout<<image.array[99][22][10]<<endl;
}
This way is certainly simple, and works fine. My question is whether this way is the recommended way to do this kind of thing, or whether it will have a very poor performance (since I don't have anything to compare to, I am clueless). Bear in mind that I need a method which works in 6 and 7 dimensions too.
I would welcome any advice as to whether this is good or bad code :-)
Thanks in advance for any help!