矩阵与向量相乘:当矩阵的列数与向量的行数相等时,用矩阵的第i行乘以向量,并输出结果向量,否则输出"Bad multiplying Matrix with Vector."。 函数接口定义: int& Matrix::operator()(int i,int j); ostream& operator<<(ostream& out,const Vector& x); Vector operator*(Matrix& mat,Vector& vex); int& Matrix::operator()(int i,int j):返回第i行第j列的矩阵元素(可作左值),应有下标越界检查,如果越界则输出信息"Matrix index out of range."; ostream& operator<<(ostream& out,const Vector& x):将向量x输出到输出流out对象。为能达到连续输入对象的效果,设置返回类型为引用; Vector operator*(Matrix& mat,Vector& vex):参数为矩阵mat、向量vex,返回二者的乘积。
时间: 2024-03-10 20:48:18 浏览: 220
向量与矩阵的基本运算
以下是代码实现:
```
#include<iostream>
#include<vector>
using namespace std;
class Matrix{
private:
vector<vector<int>> mat;
int row, col;
public:
Matrix(int r, int c): row(r), col(c){
mat.resize(row);
for(int i=0; i<row; i++){
mat[i].resize(col);
}
}
int& operator()(int i, int j){
if(i>=row || j>=col){
cout << "Matrix index out of range." << endl;
exit(1);
}
return mat[i][j];
}
friend ostream& operator<<(ostream& out, const Matrix& m){
for(int i=0; i<m.row; i++){
for(int j=0; j<m.col; j++){
out << m(i,j) << " ";
}
out << endl;
}
return out;
}
friend Vector operator*(Matrix& mat, Vector& vex);
};
ostream& operator<<(ostream& out,const Vector& x){
for(int i=0; i<x.size(); i++){
out << x[i] << " ";
}
return out;
}
Vector operator*(Matrix& mat, Vector& vex){
if(mat.col != vex.size()){
cout << "Bad multiplying Matrix with Vector." << endl;
exit(1);
}
Vector res(mat.row);
for(int i=0; i<mat.row; i++){
res[i] = 0;
for(int j=0; j<mat.col; j++){
res[i] += mat(i,j) * vex[j];
}
}
return res;
}
int main(){
Matrix m(2, 2);
m(0,0) = 1; m(0,1) = 2;
m(1,0) = 3; m(1,1) = 4;
cout << m;
Vector v(2);
v[0] = 1; v[1] = 2;
Vector res = m * v;
cout << res;
return 0;
}
```
注意,这段代码中的 `Vector` 类型需要按照实际情况进行定义,否则会编译错误。
阅读全文