As we all know, C ++ does not provide the default matrix type. But most of the time we can
Following the C usage, you can declare a two-dimensional array to declare the matrix. This article describes another method,
To implement a matrix class and express the concept of a two-dimensional array. The specific implementation is a two-dimensional vector.
# Ifndef matrix_h
# Define matrix_h
# Include <vector>
Using STD: vector;
Template <typename T>
Class Matrix
{
PRIVATE:
Vector <vector <t> vv;
Int row;
Int Col;
Public:
Matrix (INT rows, int Cols): VV (rows), row (rows), COL (Cols)
{
For (INT I = 0; I <row; ++ I) // The only note is how to construct a two-dimensional vector. First construct a vector <>,
// Initialize the length of the vector.
{
VV [I]. Resize (Cols );
}
}
Const vector <t> & operator [] (INT row) const
{
If (row> = This-> row)
{
Throw "Index out of range"; // here we can throw a defined exception or not, because the vector will also check whether the index is out of bounds.
}
Return VV [row];
}
Vector <t> & operator [] (INT row) // non-const version, used for writing. Generally, the compiler automatically selects the matching function for calling.
{
If (row> = This-> row)
{
Throw "Index out of range ";
}
Return VV [row];
}
Int getrownum () const {return row;} // gets the number of rows
Int getcolnum () const {return Col;} // gets the number of columns.
};
# Endif
Here we do not need to define the copy constructor and the value assignment constructor, because the default one is enough.
The above code has been compiled and tested by vs2008.