fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <typename T>
  5. class Matrix {
  6. private:
  7. int rows, cols;
  8. T** data;
  9.  
  10. public:
  11.  
  12. Matrix(int r, int c) : rows(r), cols(c) {
  13. data = new T*[rows];
  14. for (int i = 0; i < rows; ++i)
  15. data[i] = new T[cols];
  16. }
  17.  
  18.  
  19. ~Matrix() {
  20. for (int i = 0; i < rows; ++i)
  21. delete[] data[i];
  22. delete[] data;
  23. }
  24.  
  25. void input() {
  26. for (int i = 0; i < rows; ++i)
  27. for (int j = 0; j < cols; ++j)
  28. cin >> data[i][j];
  29. }
  30.  
  31.  
  32. void print() const {
  33. for (int i = 0; i < rows; ++i) {
  34. for (int j = 0; j < cols; ++j)
  35. cout << data[i][j] << " ";
  36. cout << endl;
  37. }
  38. }
  39. Matrix<T> operator-(const Matrix<T>& other) {
  40. if (rows != other.rows || cols != other.cols)
  41. throw runtime_error("Розміри матриць не співпадають!");
  42.  
  43. Matrix<T> result(rows, cols);
  44. for (int i = 0; i < rows; ++i)
  45. for (int j = 0; j < cols; ++j)
  46. result.data[i][j] = data[i][j] - other.data[i][j];
  47.  
  48. return result;
  49. }
  50. };
  51.  
  52. int main() {
  53. Matrix<int> A(2, 2);
  54. Matrix<int> B(2, 2);
  55.  
  56. A.input();
  57.  
  58. B.input();
  59.  
  60. Matrix<int> C = A - B;
  61.  
  62. C.print();
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0.01s 5320KB
stdin
2 4 3 2 

3 2 5 1 
stdout
-1 2 
-2 1