A dynamic array is an array data structure that can be resized and which allows elements to be added or removed.
7-11-12 UPDATE Optimization HELP by FirstMate :)
leave comments
//creation of dynamic multidimensional arrays?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//For creating one dimension array of 4 integers
int *ptr1;
ptr1 = new int[4];
for( int i = 0 ; i < 4 ; i++)
{
ptr1[i] = i+1;
}
cout << "\nOne dimension array of 4 integers:\n";
for( int i = 0 ; i < 4 ; i++)
{
cout << " " << ptr1[i] ;
}
cout << endl << endl;
//for creating two dimensional array of 3 by 4 integers
int **ptr2;
ptr2 = new int*[3];
for( int i = 0 ; i < 3 ; i++)
{
ptr2[i] = new int[4];
}
for( int i = 0 ; i < 3 ; i++)
{
for ( int j = 0 ; j < 4 ; j++)
{
ptr2[i][j] = i * 4 + j;
}
}
cout << "\nTwo dimensions array of 3 by 4 integers:\n";
for( int i = 0 ; i < 3 ; i++)
{
for ( int j = 0 ; j < 4 ; j++)
{
cout << setw(4) << right << ptr2[i][j] << " ";
}
cout << endl;
}
//for creating three dimensional array of 2 by 3 by 4 double float
double ***ptr3;
ptr3 = new double**[2];
for( int i = 0 ; i < 2 ; i++)
{
ptr3[i] = new double*[3];
for( int j = 0 ; j < 3 ; j++)
{
ptr3[i][j] = new double[4];
for( int k = 0 ; k < 4 ; k++)
{
ptr3[i][j][k] = ( i * 3 + j ) * 4.1 + k * 0.1;
}
}
}
cout << "\nThree dimensions array of 2 by 3 by 4 double float :\n";
for( int i = 0 ; i < 2 ; i++)
{
for( int j = 0 ; j < 3 ; j++)
{
for( int k = 0 ; k < 4 ; k++)
{
cout <<"\nptr3(" << i << "," << j << "," << k << ") = " << setprecision(4) <<
{
ptr3[i][j][k];
}
}
}
}
return 0;
}
Leave Comments!!!
Consider it? If it's a matter of performance (and I'm not expert on the matter), in your snippet you're iterating so much more than necessary. Consider your 2x3x4 example. Mine would iterate (234) or 24 times. In your case, you loop 2 + (23) + (23*4) or 32 times. And these are just small dimensions. Again, I'm not too knowledgeable but surely you can see the optimization in this.
I'm not sure if this was done more out of demonstrating the code, but why not take:
double ***ptr3;
ptr3 = new double**[2];
for( int i = 0 ; i < 2 ; i++)
{
ptr3[i] = new double*[3];
}
for( int i = 0 ; i < 2 ; i++)
{
for( int j = 0 ; j < 3 ; j++)
{
ptr3[i][j] = new double[4];
}
}
for( int i = 0 ; i < 2 ; i++)
{
for( int j = 0 ; j < 3 ; j++)
{
for( int k = 0 ; k < 4 ; k++)
{
ptr3[i][j][k] = ( i * 3 + j ) * 4.1 + k * 0.1;
}
}
}
And make it:
double ***ptr3;
ptr3 = new double**[2];
for( int i = 0 ; i < 2 ; i++)
{
ptr3[i] = new double*[3];
for( int j = 0 ; j < 3 ; j++)
{
ptr3[i][j] = new double[4];
for( int k = 0 ; k < 4 ; k++)
{
ptr3[i][j][k] = ( i * 3 + j ) * 4.1 + k * 0.1;
}
}
}