// 头文件matrix.h
#include <vector>
using namespace std;
template <typename T>
class matrix
{
public:
matrix( int numRows = 1, int numCols = 1, const T& initVal = T() );
vector<T> & operator[]( int i );
const vector<T> & operator[]( int i ) const;
int rows() const;
int cols() const;
void resize( int numRows, int numCols );
private:
int nRow, nCols;
vector< vector<T> > mat;
};
//源文件 matrix.cpp
#include <iostream>
#include <string>
#include "matrix.h"
template <typename T>
T matSum( const matrix<T>& mat )
{
T sum = T();
int i, j;
for( i = 0; mat.rows(); i++ )
{
for( j = 0; mat.cols(); j++ )
{
sum += mat[i][j];
}
}
return sum;
}
template <typename T>
matrix<T>::matrix( int numRows, int numCols, const T& initVal ) :
nRow( numRows ), nCols( numCols ),
mat( numRows, vector<T> ( numCols, initVal ) )
{
}
template <typename T>
vector<T> & matrix<T>::operator[]( int i )
{
if( i < 0 || i > nRow )
{
cerr << i <<" is in the scale of matrix! " << endl;
exit( -1 );
}
return mat[i];
}
template <typename T>
const vector<T> & matrix<T>::operator[]( int i ) const
{
if( i < 0 || i > nRow )
{
cerr << i <<" is in the scale of matrix! " << endl;
exit( -1 );
}
return mat[i];
}
template <typename T>
int matrix<T>::rows() const
{
return nRow;
}
template <typename T>
int matrix<T>::cols() const
{
return nCols;
}
template <typename T>
void matrix<T>::resize( int numRows, int numCols )
{
if( numRows < 0 || numCols < 0 )
{
cerr << "rows and cols cannot be assigned to the minus number!" << endl;
exit( -1 );
}
mat.reserve( numRows );
for( int i = 0; i < numRows; i++ )
{
mat[i].reserve( numCols );
}
nRow = numRows;
nCols = numCols;
}
int main( int argc, char **argv )
{
matrix<int> intMat(5,5,5);
for( int i = 0; i < intMat.rows(); i++ )
{
for( int j = 0; j < intMat.cols(); j++ )
{
cout << intMat[i][j] << " ";
}
cout << endl;
}
cout << endl;
intMat.resize( 2, 5 );
for( int i = 0; i < intMat.rows(); i++ )
{
for( int j = 0; j < intMat.cols(); j++ )
{
cout <<intMat[i][j] << " ";
}
cout << endl;
}
cout << endl;
system("Pause");
return 0;
}
//感觉写这些东西还是不灵活,不会变通、郁闷