要求实现矩阵数乘、矩阵加法和减法。可以用户从键盘输入矩阵或者从文件读取矩阵
main.cpp源文件
#include "matrix.h"
int main(){
vector<int> a;
int col;
cout<<"输入矩阵列数"<<endl;
cin>>col;
cout<<"输入矩阵"<<endl;
a = CMatrix<int>::input_matrix();
CMatrix<int> m(3,a);
cout<<"显示矩阵m"<<endl;
m.show();
CMatrix<int> n;
cout<<"从文件读取矩阵"<<endl;
n.InFile("matrix.txt");
cout<<"显示矩阵n"<<endl;
n.show();
cout<<"矩阵m数乘,输入数值"<<endl;
int k;
cin>>k;
CMatrix<int> z = m*k;
z.show();
cout<<"矩阵加法m+n"<<endl;
z = m+n;
z.show();
cout<<"矩阵减法m-n"<<endl;
z = m-n;
z.show();
return 0;
}
输入矩阵的文件
3
4 2 5 4 1 7 9 9 0
matrix.h头文件
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
template<class T> class CMatrix{
public:
~CMatrix(){}
CMatrix(){}
//构造函数
CMatrix(int c,vector<T> argV){
column = c;
//清空容器
vector<T>().swap(v);
//赋值容器
for(int i=0; i<argV.size(); i++){
v.push_back(argV.at(i));
}
}
//显示矩阵
void show(){
puts("");
for(int i=0; i<v.size(); i++){
printf("%.2lf ",(double)v.at(i));
if(i%column == column-1){//换行显示
puts("");
}
}
}
//从文件读取
void InFile(char *fileName){//fisrt row is column number,second row is value
ifstream iFile(fileName,ios::in);
if(!iFile.is_open()){
cerr<<"从文件读取矩阵失败"<<endl;
return;
}
vector<T>().swap(v);
char ch[1024] = {0};
iFile.getline(ch,sizeof(ch));
sscanf(ch,"%d",&column);
T value;
while(iFile>>value){
v.push_back(value);
}
iFile.close();
}
//重载运算符*
CMatrix operator*(const int &a)const{
vector<T> vv;
//运算结果放入新的容器
for(int i=0; i<v.size(); i++){
vv.push_back(v.at(i)*a);
}
//重新制作一个矩阵类
CMatrix m(column, vv);
return m;
}
//重载运算符+
CMatrix operator+(const CMatrix &a)const{
vector<T> vv;
for(int i=0; i<v.size(); i++){
vv.push_back(v.at(i)+a.v.at(i));
}
CMatrix m(column, vv);
return m;
}
//重载运算符-
CMatrix operator-(const CMatrix &a)const{
vector<T> vv;
for(int i=0; i<v.size(); i++){
vv.push_back(v.at(i)-a.v.at(i));
}
CMatrix m(column, vv);
return m;
}
//用户输入获取矩阵容器
static vector<T> input_matrix(){
T n;
vector<T> vv;
while(cin>>n){
if(cin.get()=='\n'){
vv.push_back(n);
break;
}
vv.push_back(n);
}
return vv;
}
//成员变量
vector<T> v;//矩阵值
int column;//矩阵列数
};
typedef CMatrix<int> matrix;//自定义类型
typedef CMatrix<float> matrix_f;//自定义类型
运算结果
输入矩阵列数
3
输入矩阵
1 2 3 4 5 6 7 8 9
显示矩阵m
1.00 2.00 3.00
4.00 5.00 6.00
7.00 8.00 9.00
从文件读取矩阵
显示矩阵n
4.00 2.00 5.00
4.00 1.00 7.00
9.00 9.00 0.00
矩阵m数乘,输入数值
3
3.00 6.00 9.00
12.00 15.00 18.00
21.00 24.00 27.00
矩阵加法m+n
5.00 4.00 8.00
8.00 6.00 13.00
16.00 17.00 9.00
矩阵减法m-n
-3.00 0.00 -2.00
0.00 4.00 -1.00
-2.00 -1.00 9.00