fork download
  1. #include <cstdint>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5.  
  6. template <typename T>
  7. class Matrix
  8. {
  9. public:
  10. Matrix(std::size_t rows, std::size_t columns);
  11. Matrix(std::initializer_list<std::initializer_list<T>> init);
  12. auto rows() const -> std::size_t;
  13. auto columns() const -> std::size_t;
  14. auto operator()(std::size_t i, std::size_t j) const -> const T&;
  15. auto operator()(std::size_t i, std::size_t j) -> T&;
  16. private:
  17. const std::size_t rows_;
  18. const std::size_t columns_;
  19. std::vector<T> elements_;
  20.  
  21. };
  22.  
  23. template <typename T>
  24. Matrix<T>::Matrix(std::size_t rows, std::size_t columns)
  25. : rows_{ rows }, columns_{ columns }, elements_( rows * columns )
  26. {
  27. }
  28.  
  29. template <typename T>
  30. Matrix<T>::Matrix(std::initializer_list<std::initializer_list<T>> init)
  31. : Matrix{
  32. init.size(),
  33. std::max(
  34. init,
  35. [](const auto& a, const auto& b) {
  36. return a.size() < b.size();
  37. }
  38. ).size()
  39. }
  40. {
  41. std::size_t i = 0;
  42. for (const auto& row : init)
  43. {
  44. if (i >= rows())
  45. break;
  46. std::size_t j = 0;
  47. for (const auto& value : row)
  48. {
  49. if (j >= columns())
  50. break;
  51. (*this)(i, j) = value;
  52. ++j;
  53. }
  54. ++i;
  55. }
  56. }
  57.  
  58. template <typename T>
  59. auto Matrix<T>::rows() const -> std::size_t
  60. {
  61. return rows_;
  62. }
  63.  
  64. template <typename T>
  65. auto Matrix<T>::columns() const -> std::size_t
  66. {
  67. return columns_;
  68. }
  69.  
  70. template <typename T>
  71. auto Matrix<T>::operator()(std::size_t i, std::size_t j) const -> const T&
  72. {
  73. return elements_[ i * columns() + j];
  74. }
  75.  
  76. template <typename T>
  77. auto Matrix<T>::operator()(std::size_t i, std::size_t j) -> T&
  78. {
  79. return elements_[ i * columns() + j];
  80. }
  81.  
  82. template <typename T>
  83. std::ostream& operator<<(std::ostream& out, const Matrix<T>& m)
  84. {
  85. out << typeid(T).name() << m.rows() << "x" << m.columns();
  86. out << "{ ";
  87. for (std::size_t i = 0; i < m.rows(); ++i)
  88. {
  89. if (i > 0)
  90. out << ", ";
  91. out << "{ ";
  92. for (std::size_t j = 0; j < m.columns(); ++j)
  93. {
  94. if (j > 0)
  95. out << ", ";
  96. out << m(i, j);
  97. }
  98. out << " }";
  99. }
  100. out << " }";
  101. return out;
  102. }
  103.  
  104. auto main() -> int
  105. {
  106. Matrix<float> m
  107. {
  108. { 1, 2, 3 },
  109. { 4, 5, 6 },
  110. { 7, 8, 9 }
  111. };
  112.  
  113. std::cout << m << std::endl;
  114. }
Success #stdin #stdout 0s 4280KB
stdin
Standard input is empty
stdout
f3x3{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }