59 template<
typename T,
size_t rowCount,
size_t colCount>
62 static_assert(rowCount > 0 && colCount > 0,
"rowCount and colCount must be > 0");
65 using Storage = std::array<T, rowCount * colCount>;
76 using Iterator =
typename Storage::iterator;
86 static constexpr
size_t rows{ rowCount };
91 static constexpr
size_t cols{ colCount };
97 explicit Matrix(
const std::array<T, colCount * rowCount> &arrArr)
102 template<
typename Iterator>
105 if(std::distance(beginIt, endIt) !=
rows *
cols)
107 throw std::out_of_range(
"Input size does not match matrix size. Expected " + std::to_string(
rows *
cols)
108 +
" items, got " + std::to_string(std::distance(beginIt, endIt)) +
" items.");
111 std::copy(beginIt, endIt, m_mat.begin());
115 explicit Matrix(std::initializer_list<T> values)
116 :
Matrix{ values.begin(), values.end() }
120 explicit Matrix(std::initializer_list<std::initializer_list<T>> values)
122 if(values.size() !=
rows)
124 throw std::out_of_range(
"Input size does not match matrix size. Expected " + std::to_string(
rows)
125 +
"rows, got " + std::to_string(values.size()) +
" rows");
128 auto iterator =
begin();
129 for(
const auto &row : values)
131 if(row.size() !=
cols)
133 throw std::out_of_range(
"Input size does not match matrix size. Expected all rows to be of size "
134 + std::to_string(
cols) +
", got row with " + std::to_string(row.size())
137 for(
const auto &value : row)
139 *(iterator++) = value;
147 return m_mat.begin();
159 return m_mat.cbegin();
169 T &
at(
size_t row,
size_t col)
171 throwIfOutOfBounds(row, col);
172 return m_mat[row *
cols + col];
176 const T &
at(
size_t row,
size_t col)
const
178 throwIfOutOfBounds(row, col);
179 return m_mat[row *
cols + col];
185 return m_mat[row *
cols + col];
189 const T &
operator()(
size_t row,
size_t col)
const
191 return m_mat[row *
cols + col];
198 std::stringstream ss;
200 for(
size_t row = 0; row < rowCount; row++)
202 ss << (row == 0 ?
"[" :
"\n [");
203 for(
size_t col = 0; col < colCount; col++)
205 const auto value{ m_mat[row * colCount + col] };
206 ss << (value >= 0 ?
" " :
"") << std::to_string(value);
207 ss << (col == colCount - 1 ?
"" :
", ");
209 ss << (row == rowCount - 1 ?
"]" :
"], ");
216 static void throwIfOutOfBounds(
size_t row,
size_t col)
220 throw std::out_of_range(
"Trying to access row with index " + std::to_string(row)
221 +
", but allowed range is [0, " + std::to_string(
rows - 1) +
"]");
225 throw std::out_of_range(
"Trying to access column with index " + std::to_string(col)
226 +
", but allowed range is [0, " + std::to_string(
cols - 1) +
"]");
234 template<
typename T,
size_t rowCount,
size_t colCount>
235 std::ostream &
operator<<(std::ostream &stream,
const Matrix<T, rowCount, colCount> &matrix)
237 return stream << matrix.toString();