matrix.cpp (2294B)
1 #include <iostream> 2 3 class matrix{ 4 int row, col, **p; 5 public: 6 int getR(){ 7 return this->row; 8 }; 9 int getC(){ 10 return this->col; 11 }; 12 matrix(){ 13 p = NULL; 14 }; 15 bool initMatrix(int r, int c){ 16 row = r; col = c; 17 p = new int *[row]; 18 for (int i = 0; i < row; i++) { 19 p[i] = new int [col]; 20 } 21 if(p == NULL){ 22 std::cout << "Insufficient memory." << '\n'; 23 return 1; 24 } 25 return 0; 26 }; 27 bool operator==(matrix other){ 28 if(this->row == other.row && this->col == other.col) 29 return true; 30 return false; 31 }; 32 33 matrix operator+(matrix other){ 34 matrix r; 35 if(r.initMatrix(other.getR(), other.getC())) 36 std::cout << "Insufficient memory." << '\n'; 37 else{ 38 for(int i = 0; i < row; i++) 39 for(int j = 0; j < col; j++) 40 r.p[i][j] = this->p[i][j] + other.p[i][j]; 41 return r; 42 } 43 }; 44 45 matrix operator-(matrix other){ 46 matrix r; 47 if(r.initMatrix(other.getR(), other.getC())) 48 std::cout << "Insufficient memory." << '\n'; 49 else{ 50 for(int i = 0; i < row; i++) 51 for(int j = 0; j < col; j++) 52 r.p[i][j] = this->p[i][j] - other.p[i][j]; 53 return r; 54 } 55 }; 56 57 void getData(){ 58 for (int i = 0; i < row; i++) 59 for(int j = 0; j < col; j++) 60 std::cin >> p[i][j]; 61 }; 62 void operator <<(int x){ 63 for (int i = 0; i < row; i++){ 64 for(int j = 0; j < col; j++) 65 std::cout << p[i][j] << " "; 66 std::cout << std::endl; 67 } 68 }; 69 }; 70 71 int main(){ 72 matrix m, n, a, s; 73 int r, c; 74 do{ 75 std::cout << "Enter rows and columns of first matrix: "; 76 std::cin >> r >> c; 77 if(r < 1 || c < 1) 78 std::cout << "Invalid size, try again." << '\n'; 79 }while (r < 1 || c < 1); 80 if(m.initMatrix(r, c)) 81 return 0; 82 do{ 83 std::cout << "Enter rows and columns of second matrix: "; 84 std::cin >> r >> c; 85 if(r < 1 && c < 1) 86 std::cout << "Invalid size, try again." << '\n'; 87 }while (r < 1 && c < 1); 88 if(n.initMatrix(r, c)) 89 return 0; 90 std::cout << "Enter first matrix:" << '\n'; 91 m.getData(); 92 std::cout << "Enter second matrix: " << '\n'; 93 n.getData(); 94 if(m == n) { 95 a = m + n; 96 a << 0; 97 s = m - n; 98 s << 0; 99 } 100 else { 101 std::cout << "Incompatible.\n"; 102 m << 0; 103 n << 0; 104 } 105 return 0; 106 }