一年前刚刚告别了数值计算的学习,也就注定了我此生与矩阵计算越走越远,说来还有些伤感——今天帮助小学弟(妹)写c++,大致是类入门的一些东西。名义上我也是翻过Primer的人,但是要说实践经历,还真是几乎零经验。总之,之前研究过的矩阵类算是用上了。
矩阵类
之前自己用std::vector实现过,也玩过boost库里边的矩阵类(boost/numeric/bindings; boost真是一个神奇的东西),还有整个库只包含头文件的Eigen,和号称能翻译matlab的Armadillo,此外听说MKL,tnt,OpenBlas,OpenCV,甚至是itpp(一个符号计算库)都能用来算矩阵。自己实现的用起来就是舒服。部分实现如下:
class matrix: public vector< vector<double> >
{
size_t m,n;
public:
matrix() {}
matrix(const size_t a, const size_t b): m(a), n(b)
{
this -> resize(m);
for (size_t i = 0; i < m ; i++ )
(*this)[i].resize(n);
}
double operator () (const size_t i, const size_t j) const
{
return (*this)[i][j];
}
matrix& operator = (const matrix& rhs)
{
m = rhs.m;
n = rhs.n;
this -> resize(m);
for (size_t i = 0; i < m ; i++ )
{
(*this)[i].resize(n);
for (size_t j = 0; j < n; j++)
(*this)[i][j] = rhs[i][j];
}
return *this;
}
};
总之,就是两重vector直接继承过来。这样最大的好处是使用方便。比方说: