矩阵乘法
#include <iostream>
#include <iomanip>
using namespace std;
class matrix{
private:
int row,column;
int **mat;
public:
matrix(const matrix& mx){
this->row=mx.row;
this->column=mx.column;
this->mat=new int*[row];
for (int i = 0; i <row ; ++i) {
this->mat[i]=new int[column];
for (int j = 0; j <column ; ++j) {
this->mat[i][j]=mx.mat[i][j];
}
}
}
matrix(int r,int c){
row=r;
column=c;
mat=new int*[row];
for (int i = 0; i <row ; ++i) {
mat[i]=new int[column];
for (int j = 0; j <column ; ++j) {
mat[i][j]=0;
}
}
}
~matrix(){
for (int i = 0; i <row ; ++i) {
delete []mat[i];
}
delete []mat;
}
void read(){
for (int j = 0; j <row ; ++j) {
for (int i = 0; i <column ; ++i) {
cin>>mat[j][i];
}
}
}
matrix operator*(matrix& mt){
if(this->row==1&&this->column==1){
for (int i = 0; i < mt.row; ++i) {
for (int j = 0; j <mt.column ; ++j) {
mt.mat[i][j]=this->mat[0][0]*mt.mat[i][j];
}
}
return mt;
}else{
matrix rs(this->row,mt.column);
for (int i = 0; i < this->row; ++i) {
for (int j = 0; j <mt.column ; ++j) {
for (int k = 0; k <mt.row ; ++k) {
rs.mat[i][j]+=this->mat[i][k]*mt.mat[k][j];
}
}
}
return rs;
}
}
void display(){
for (int i = 0; i <row ; ++i) {
for (int j = 0; j <column ; ++j) {
cout<<setw(10)<<mat[i][j];
}
cout<<endl;
}
}
};
int main()
{
int r,c;
cin>>r>>c;
matrix m1(r,c);
m1.read();
int r1,c1;
cin>>r1>>c1;
matrix m2(r1,c1);
m2.read();
if(c==r1||r==1&&c==1){
matrix m3=m1*m2;
m3.display();
}
else{
cout<<"Invalid Matrix multiplication!";
}
return 0;
}
#include <iomanip>
using namespace std;
class matrix{
private:
int row,column;
int **mat;
public:
matrix(const matrix& mx){
this->row=mx.row;
this->column=mx.column;
this->mat=new int*[row];
for (int i = 0; i <row ; ++i) {
this->mat[i]=new int[column];
for (int j = 0; j <column ; ++j) {
this->mat[i][j]=mx.mat[i][j];
}
}
}
matrix(int r,int c){
row=r;
column=c;
mat=new int*[row];
for (int i = 0; i <row ; ++i) {
mat[i]=new int[column];
for (int j = 0; j <column ; ++j) {
mat[i][j]=0;
}
}
}
~matrix(){
for (int i = 0; i <row ; ++i) {
delete []mat[i];
}
delete []mat;
}
void read(){
for (int j = 0; j <row ; ++j) {
for (int i = 0; i <column ; ++i) {
cin>>mat[j][i];
}
}
}
matrix operator*(matrix& mt){
if(this->row==1&&this->column==1){
for (int i = 0; i < mt.row; ++i) {
for (int j = 0; j <mt.column ; ++j) {
mt.mat[i][j]=this->mat[0][0]*mt.mat[i][j];
}
}
return mt;
}else{
matrix rs(this->row,mt.column);
for (int i = 0; i < this->row; ++i) {
for (int j = 0; j <mt.column ; ++j) {
for (int k = 0; k <mt.row ; ++k) {
rs.mat[i][j]+=this->mat[i][k]*mt.mat[k][j];
}
}
}
return rs;
}
}
void display(){
for (int i = 0; i <row ; ++i) {
for (int j = 0; j <column ; ++j) {
cout<<setw(10)<<mat[i][j];
}
cout<<endl;
}
}
};
int main()
{
int r,c;
cin>>r>>c;
matrix m1(r,c);
m1.read();
int r1,c1;
cin>>r1>>c1;
matrix m2(r1,c1);
m2.read();
if(c==r1||r==1&&c==1){
matrix m3=m1*m2;
m3.display();
}
else{
cout<<"Invalid Matrix multiplication!";
}
return 0;
}