c++:Vector二维数组在矩阵计算中的应用
(1).矩阵类的定义
class Box
{
private:
int m,n;
vector<double> line; //数据容器(一维)
vector< vector<double> >boxinfo; //容器容器(二维)
public:
Box(int a,int b){m = a;n = b;}
void printbox();
void inputbox();
bool squarebox();
Box operator + (Box &b1); //重载运算符
Box operator - (Box &b1);
Box operator * (Box &b1);
};
(2).输入
//填满了压进去
void Box::inputbox()
{
for (int i = 0; i < this->m; ++i)
{
for(int j = 0; j < this->n; ++ j)
{
double temp;
cin >> temp;
line.push_back(temp);
}
boxinfo.push_back(line);
line.erase(line.begin(), line.end());
}
}
(3).输出
//直接用二维坐标访问
void Box::printbox()
{
cout << "Display your Box" << endl;
for (int i = 0; i < this->m; ++i)
{
for(int j = 0; j < this->n; ++ j)
{
cout << boxinfo[i][j]<< " ";
}
cout << endl;
}
}
(4)重载运算,以乘法为例
//注意m,n和line的归属问题。
Box Box::operator * (Box &b1)
{
Box b2(this->m,b1.n);
if(this ->n != b1.m)
{
cerr << "Error Input(m!=n)" <<endl;
return b2;
}
for (int i = 0; i < this->m; ++i)
{
for(int j = 0; j < b1.n; ++ j)
{
int temp (0);
for(int k = 0; k < this ->n ; ++k)
{
temp += boxinfo[i][k] * b1.boxinfo[k][j];
}
b2.line.push_back(temp);
}
b2.boxinfo.push_back(b2.line);
b2.line.erase(b2.line.begin(), b2.line.end());
}
return b2;
}