【发布时间】:2011-04-12 10:13:22
【问题描述】:
我正在尝试在 C++ 中构建一个模板化的 Matrix 类。下面是它的实现。 到目前为止,我实现了两个运算符 +,+= 只是为了了解它的外观,我认为最好在继续之前征求反馈意见。
整个实现是公开的,也没有明确的边界/错误检查,这是因为它并不是一个完整的矩阵库,因此避免了不必要的代码。
如果有人可以对此发表评论并提出一些改进或建议,那将非常有帮助。
谢谢。
template<class T>
class Matrix
{
public:
int r,c;
vector< vector< T > >mat;
Matrix() {}
// Constructor to set the size of the matrix
Matrix(int _r,int _c)
{
r=_r;c=_c;
mat.resize(r);
for(int i=0;i<r;i++)
mat[i].resize(c);
}
// Constructor to build a matrix from a C 2d array
// Pointer to the first element is passed (&arr[0][0])
Matrix(T *arr,int _r,int _c)
{
r=_r;c=_c;
mat.resize(r);
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
mat[i].push_back(arr[i*c+j]);
}
template<typename U>
Matrix<T>& operator +=(const Matrix<U>&M)
{
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
mat[i][j]+=static_cast<T>(M.mat[i][j]);
return *this;
}
template<typename U>
Matrix<T> operator +(const Matrix<U>&M)
{
Matrix<T>tmp=*this;
return tmp+=M;
}
};
template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
in>>M.r>>M.c;
Matrix<T>tmp(M.r,M.c);
for(int i=0;i<M.r;i++)
for(int j=0;j<M.c;j++)
in>>tmp.mat[i][j];
M=tmp;
return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
for(int i=0;i<M.r;i++)
{
for(int j=0;j<M.c;j++)
cout<<M.mat[i][j]<<" ";
cout<<endl;
}
return out;
}
编辑: 谢谢大家的建议。
我只有一个小问题,说我确实想实现错误检查(例如:检查边界、有效参数等)但是我确实希望为用户提供一个完全禁用错误检查的选项,有没有实现这个的好方法? 我需要的是类似示例:`ios_base::sync_with_stdio(0);。 再次感谢。
【问题讨论】:
-
您假设 RHS 的尺寸与 LHS 相同 - 这可能不是故意的。