fork download
  1. #include <iostream>
  2. #include <valarray>
  3.  
  4. template<typename T>
  5. class Matrix {
  6. std::valarray<T> data;
  7. size_t columns;
  8. public:
  9. Matrix(size_t rows, size_t columns)
  10. : data(rows*columns), columns(columns) {}
  11.  
  12. T operator()(size_t row, size_t col) const
  13. {
  14. return data[row + columns*col];
  15. }
  16.  
  17. T& operator()(size_t row, size_t col)
  18. {
  19. return data[row + columns*col];
  20. }
  21.  
  22. Matrix& operator+=(const Matrix& other)
  23. {
  24. data += other.data;
  25. return *this;
  26. }
  27. };
  28.  
  29. template<typename T>
  30. Matrix<T> operator+(Matrix<T> lhs, const Matrix<T>& rhs)
  31. {
  32. return lhs += rhs;
  33. }
  34.  
  35. int main()
  36. {
  37. Matrix<int> m1(2,2);
  38. m1(0,0) = 1; m1(0,1) = 2;
  39. m1(1,0) = 3; m1(1,1) = 4;
  40.  
  41. Matrix<int> m2 = m1;
  42. Matrix<int> m3 = m1 + m2;
  43.  
  44. std::cout << m3(0,0) << ' ' << m3(0,1) << '\n'
  45. << m3(1,0) << ' ' << m3(1,1) << '\n';
  46. }
  47.  
Success #stdin #stdout 0.02s 2856KB
stdin
Standard input is empty
stdout
2 4
6 8