Correct way of dynamic memory allocation for high-dimensional arrays in C++? -
i wondering easiest , of course accurate way dynamic memory allocation 4-d array in c++. know following:
double**** a; = new double***[s1]; (i = 0; < s1; i++) { a[i] = new double**[s2]; (j = 0; j < s2; j++) { a[i][j] = new double*[s3]; (k = 0; k < s3; k++) { a[i][j][k] = new double[s4]; } } } to declare a 4-d array of dimensions s1xs2xs3xs4.
however, above not safe. in sense if 1 of news fail allocate memory loops continue without noticing this.
to make above bit safer, can enclose in try/catch block code not continue after bad_alloc has been thrown new , code not try access non-existent memory elements , program can halt @ point.
this ok exception memory has been allocated not released before program finishes. theoretically values of i, j, , k must able precisely memory elements allocated , release them. cannot think of straightforward way of doing it.
for 2-d case this:
double** a; try { = new double*[s1]; } catch(bad_alloc& ba) { delete[] a; throw ba; // or end program } try { (i = 0; < s1; i++) a[i] = new double[s2]; } catch(bad_alloc& ba) { while(--i) { delete[] a[i]; } delete[] a; throw ba; // or end prog. } the above generalized higher dimensional arrays guess ugly! wonder if there better way doing that?
i guess should mention in case a[i][j][k] vector few non-zero elements. hence, take s3 big number of non-zero elements (and take care of mapping indices , ... later). s3, however, depends on j. that's why using traditional memory allocation easier higher-level apis vector
std::vector<std::vector<std::vector<std::vector<double>>>> a; that 4d dynamic array without worry of managing exception safety (for memory allocations @ least).
if want static array:
std::array<std::array<std::array<std::array<double, n>, n>, n>, n> b; side note: if nesting far, can gain lot through refactoring.
that's why using traditional memory allocation easier higher-level apis vector
that flawed assertion. have non-sparse 4d array - gain next nothing using "traditional memory allocation" on using std::vector or std::array or boost multiarray. of same steps have take proper memory management , exception safety done (and tested) in classes, whereas custom implementation not.
Comments
Post a Comment