Skip to content

Instantly share code, notes, and snippets.

@misha-antonenko
Created March 6, 2021 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misha-antonenko/d103863fa5f6dec27a393736f95d30c3 to your computer and use it in GitHub Desktop.
Save misha-antonenko/d103863fa5f6dec27a393736f95d30c3 to your computer and use it in GitHub Desktop.
// the what has been
Matrix &Matrix::operator*=(const Matrix &m)
{
return *this = *this * m; // observe that, due to the copy-and-swap implementation
// of the assignment operator, there are no redundant copies created
}
Matrix Matrix::operator*(const Matrix &m) const
{
Matrix res(_rows, m._cols);
for (std::size_t i = 0; i < _rows; i++)
{
for (std::size_t j = 0; j < m._cols; j++)
{
for (std::size_t k = 0; k < _cols; k++)
{
res.get(i, j) += get(i, k) * m.get(k, j);
}
}
}
return res;
}
// the suggested
Matrix &Matrix::operator*=(const Matrix &m)
{
Matrix res(_rows, m._cols);
for (std::size_t i = 0; i < _rows; i++)
for (std::size_t j = 0; j < m._cols; j++)
for (std::size_t k = 0; k < _cols; k++)
{
res.get(i, j) += get(i, k) * m.get(k, j);
}
*this = res; // res gets copied, O(n)
return *this;
}
Matrix Matrix::operator*(const Matrix &m) const
{
Matrix this_copy = *this; // a copy of *this, O(n)
return this_copy *= m;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment