二維整數矩陣 和乘

1 個解答

• 5 年前
最佳解答

#include <string.h>

#include <iostream>

#include <string>

using namespace std;

template <class DD>

struct M {

public:

unsigned r,c;

DD *m;

M():r(0),c(0),m(NULL) {};

M(unsigned rows,unsigned cols):r(rows),c(cols),m(new DD[r*c]){};

~M(){if(m)delete m, m=NULL;};

M& operator=(const M& a){

if(m)delete m, m=NULL;

r=a.r, c=a.c;

m=new DD[a.r * a.c];

memcpy(m,a.m,sizeof(*m)*r*c);

return *this;

}

M(const M& a):m(0) { *this = a; }

M operator*(const M& b) {

if (c != b.r) throw 1;

M z(r,b.c);

for (unsigned i=0; i<z.r; ++i)

for (unsigned j=0; j<z.c; ++j)

for (unsigned k=z.m[i*z.c+j]=0; k<c; ++k)

z.m[i*z.c+j]+=m[i*c+k]*b.m[k*b.c+j];

return z; // M(z);

}

M operator-(const M& b) {

const M a=*this;

if (a.r != b.r || a.c != b.c) throw 1;

M z(a.r,a.c);

for (unsigned r=0; r<z.r; ++r)

for (unsigned c=0; c<z.c; ++c)

z.m[r*b.c+c]=a.m[r*b.c+c]-b.m[r*b.c+c];

return z; // M(z);

}

M operator+(const M& b) {

const M a=*this;

if (a.r != b.r || a.c != b.c) throw 1;

M z(a.r,a.c);

for (unsigned r=0; r<z.r; ++r)

for (unsigned c=0; c<z.c; ++c)

z.m[r*b.c+c]=a.m[r*b.c+c]+b.m[r*b.c+c];

return z; // M(z);

}

};

template <class DD>

ostream& operator<<(ostream& os,M<DD>& a) {

for (unsigned r=0; r<a.r; ++r,os << endl)

for (unsigned c=0; c<a.c; ++c)

os << "A[" <<r<<"]["<<c<<"]="<<a.m[a.c*r+c] << " ";

return os;

}

template <class DD>

istream& operator>>(istream& is,M<DD>& a) {

cout << "rows,cols="<<a.r<<','<<a.c<<endl;

a.m = new DD[a.r*a.c];

for (unsigned rr=0; rr<a.r; rr++) {

cout << "enter the " << rr << " row: ";

for (unsigned cc=0; cc<a.c; cc++) is >> a.m[rr*a.c+cc];

}

return is;

};

int main(void) {

M<int> a(2,3), b(3,2);

cin>>a>>b;

cout << a << endl;

M<int> d(0,0);

try{

d=(a*b);

cout<<d << endl;

} catch(int e){}

return 0;

}

• 登入以對解答發表意見