I am currently working on a matrix class and I can't decide which method is best to process a matrix transpose.
At first I did the classical way:
Matrix Matrix::Transpose()
{
Matrix M(m_cols, m_rows);
for(int i=0; i < m_rows; ++i)
{
for(int j=0; j < m_cols; ++j)
{
M(j,i) = this->m_matrix[i][j];
}
}
return M;
}
But on a second thought I was wondering if this way was better in term of memory management:
Matrix& Matrix::Transpose()
{
std::unique_ptr<Matrix> M(new Matrix(*this));
m_matrix.resize(m_cols);
for(unsigned long i = 0; i < m_matrix.size(); ++i)
{
m_matrix[i].resize(m_rows, 0.0);
}
m_rows = M->Get_Cols();
m_cols = M->Get_Rows();
for(unsigned long i=0; i < M->Get_Rows(); ++i)
{
for(unsigned long j=0; j < M->Get_Cols(); ++j)
{
this->m_matrix[j][i] = (*M)(i,j);
}
}
return *this;
}
Now both methods work, but I'm quite new to the "memory management" side of C++ and I can't really tell which one is better in terms of "good practice"...