How to make generic this function in C++ (i.e., template based) -
i use gcc version 4.6.3. want implement function allocate 2-dimensional matrices , initialize them. used following code, want template based (or generic) one. want generic function handle bool, float, , double @ same time (the procedure similar in cases). please me, or introduce me better way allocate 2d matrix.
void doublealloc2d(double ** &t, int r, int c,double initialvalue=0) { t=new double*[r]; if (!t) { if (details) std::printf ("not enough memory.(code: 461546596551)\n"); getchar(); exit(-1); } (int i=0;i<r;i++) { t[i] = new double[c]; if (!t[i]) { if (details) std::printf ("not enough memory.(code: 461651651)\n"); getchar(); exit(-1); } (int j=0;j<c;j++) t[i][j] = initialvalue; } }
you don't specify want generic, i'll guess type (and maybe dimensions). usual way create object (including containers, generic or not) in c++ define class. like:
template <typename t, int rows, int columns> class matrix { std::vector<t> mydata; public: matrix( t const& init = t() ) : mydata( rows * columns, init ) { } t* operator[]( int index ) { return &mydata[0] + index * columns; } t const* operator[]( int index ) const { return &mydata[0] + index * columns; } // ... };
if don't want rows , columns compile time constants, drop them template parameters, , add them constructor parameters. , don't forget save them.
a more complex (but still not difficult) solution use proxy class return value of operator[]
, rather t*
. frequent solution override operator()( int i, int j )
indexing, , use m( i, j )
syntax, rather m[i][j]
.
there never cause use array new in c++. c++ not c, , shouldn't try program if were.
Comments
Post a Comment