一个简单的矩阵类的实现(参照《数据结构C++语言描述》第五章)

// 头文件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;

//感觉写这些东西还是不灵活,不会变通、郁闷

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值