Al wrote:
I'd like to declare (in a Matrix class) a two-dimentional array with
user-defined coordinates. The constructor is:
Matrix(int c, int l): col(c), lin(l), a(new float[col][lin]) {}
the compiler says 'lin' should be a constant, but I want it to be
defined from the user, so what should I do? and how must 'a' be
declared??
help me please
a) Do not roll your own matrix code unless you absolutely have to. Numerical
analysis is hard. Use a library instead. There are many good linear algebra
libraries out there. Google is your friend.
b) Do not use float for numerical computations unless you know with
certainty that the precision is good enough for your needs. Beware that
linear algebra algorithms can go mad on precision.
c) If you absolutely need to run your own matrix class, do not do the memory
management by yourself. Simply do
template <typename ArithmeticType>
class Matrix
std::size_t row_size;
std::size_t col_size;
std::vector< ArithmeticType > data;
Matrix ( std::size_t rows, std::size_t cols )
: row_size ( rows )
, col_size ( cols )
, data ( rows*cols )
{}
ArithmeticType &
operator() ( std::size_t row, std::size_t col ) {
// check for bounds here if you please ...
return( this->data[row*this->cols_size + col ] );
}
ArithmeticType const &
operator() ( std::size_t row, std::size_t col ) const {
// check for bounds here if you please ...
return( this->data[ row*this->cols_size + col ] );
}
};
You might also want to have a look into std::valarray and the numeric
header.
d) Adhere to established math conventions: matrices have rows and columns,
and rows go first. Make that second nature, and bugs will go away.
e) Again: do not roll your own code.
Best
Kai-Uwe Bux