fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <memory>
  4. #include <fstream>
  5. #include <sstream>
  6.  
  7.  
  8. struct SquareMatrix
  9. {
  10. SquareMatrix(unsigned dimensions)
  11. : _dim(dimensions), _matrix(new int[_dim*_dim]) {}
  12.  
  13. unsigned dimension() const { return _dim; }
  14.  
  15. int& operator()(unsigned row, unsigned col)
  16. {
  17. return _matrix[row * _dim + col];
  18. }
  19.  
  20. int operator()(unsigned row, unsigned col) const
  21. {
  22. return _matrix[row * _dim + col];
  23. }
  24.  
  25. private:
  26. unsigned _dim;
  27. std::unique_ptr<int[]> _matrix;
  28. };
  29.  
  30. std::ostream& operator<<(std::ostream& os, const SquareMatrix& mat)
  31. {
  32. for (unsigned i = 0; i < mat.dimension(); ++i)
  33. {
  34. for (unsigned j = 0; j < mat.dimension(); ++j)
  35. os << mat(i, j) << ' ';
  36.  
  37. os << '\n';
  38. }
  39. return os;
  40. }
  41.  
  42. std::istream& operator>>(std::istream& is, SquareMatrix& mat)
  43. {
  44. for (unsigned i = 0; i < mat.dimension(); ++i)
  45. for (unsigned j = 0; j < mat.dimension(); ++j)
  46. is >> mat(i, j);
  47.  
  48. return is;
  49. }
  50.  
  51. int main()
  52. {
  53. // std::ifstream in("matrix.txt");
  54. std::istringstream in("3\n5 7 10\n5 3 2\n0 6 8");
  55.  
  56. unsigned size;
  57. in >> size;
  58.  
  59. SquareMatrix matrix(size);
  60. in >> matrix;
  61.  
  62. std::cout << matrix << '\n';
  63. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
5 7 10 
5 3 2 
0 6 8