Thursday, September 14, 2006

splitting strings in c++ using stringstream

of if you need to split a string "10 20 30 40 " in c++

You can do that using istringstream

all u need to do is

#include < sstream >

Assuming s is "10 20 30 40"

istringstream iss(s) ;

int ten , twenty , thirty , forty ;
iss >> ten >> twenty >> thirty >> forty;

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;
}