Thursday, September 14, 2006

converting 2D array into single array

This piece of snippet is written in c++ , converts a 2 dimensional Array into a single array
//
provide the size of the array to be converted with T being the data type
// invoke the function like


// int * arr = Covert2DTo1DimensionalArray ( source_array , 3 , 3 )



template < class T , int SIZE >
T* Covert2DTo1DimensionalArray( T source[SIZE][SIZE] , int width , int height ){

// the width of the new single dimensional array would be width * height
int length = width * height;

// create a new single simensional array on the heap
T * _array = new T[length];

// push values into the single dimensional array

int ctr = 0;

for(int y = 0; y <= height ; y++) {
for( int x = 0; x <= width; x++) {
_array[ctr++] = source[y][x];
}
}
return _array;
}

No comments: