我在 test.cpp 文件中得到了以下代码来实现:
cout << "Case 2: the non-static Transpose function" << endl;
{
double column[4] = {2, 1, 0, -1};
double row[3] = {2, 0, -1};
Matrix matrix = Matrix::Toeplitz(column, 4, row, 3);
cout << "The original Matrix = " << endl;
cout << matrix << endl; //This part of the code works
matrix.Transpose(); //How do I implement this?
cout << "The transposed version = " << endl;
cout << matrix << endl;
cout << "Press any key to continue ..." << flush;
system("read");
cout << endl;
}
Matrix::Toeplitz(column, 4, row, 3) 的工作方式如下:
Matrix Matrix::Toeplitz(const double* column, const int noOfRows, const double* row, const int noOfColumns){
Matrix outT(column, noOfRows, row, noOfColumns);
return outT;
}
那么我将如何实现 matrix.Transpose()?到目前为止,我的代码如下:
Matrix& Matrix::Transpose () {
double newrow[noOfRows];
for(int i=0; i<noOfRows; i++){
int index = GetIndex(i,0);
newrow[i] = data[index];
}
double newcol[noOfColumns];
for(int i=0; i<noOfColumns; i++){
int index = GetIndex(0,i);
newcol[i] = data[index];
}
Matrix outT(newcol, noOfColumns, newrow, noOfRows);
}
这对 cout<<matrix<<endl;
没有影响
我在想Matrix outT(newcol, noOfColumns, newrow, noOfRows);
应该在实现 matrix.Transpose 时向矩阵对象提供新信息(即切换列和行数组),但它一直没有工作。
这是实现 matrix.Transpose() 的正确格式 Matrix& Matrix::Transpose () 吗?
最佳答案
Matrix::Transpose
无法返回对本地声明对象的引用。这会导致很多问题。
参见 C++ Returning reference to local variable .
它必须通过复制返回(然后,函数可以是 const
,因为当前对象没有被修改):
Matrix Matrix::Transpose() const
{
double newrow[noOfRows];
for(int i=0; i<noOfRows; i++){
int index = GetIndex(i,0);
newrow[i] = data[index];
}
double newcol[noOfColumns];
for(int i=0; i<noOfColumns; i++){
int index = GetIndex(0,i);
newcol[i] = data[index];
}
return Matrix(newcol, noOfColumns, newrow, noOfRows);
}
然后,您可以这样使用它:
Matrix transposed = matrix.Transpose(); // does not modify matrix object
cout << "The transposed version = " << endl;
cout << transposed << endl;
如果返回Matrix&
,您需要让您的方法转置当前对象并返回它(return *this
),仅用于帮助调用者链接许多运算符(比如做 m.Transpose().Transpose()
)。
然后,它可以(未测试):
Matrix& Matrix::Transpose()
{
// backup old content
double* backupData = new double[noOfRows*noOfColumns];
memcpy( backupData, data, sizeof(double)*noOfRows*noOfColumns );
// change matrix geometry
int oldRowCount = noOfRows;
noOfRows = noOfColumns;
noOfColumns = oldRowCount ;
// transpose matrix by copying from backup content
for ( unsigned int line = 0; line < noOfRows ; ++line )
{
for ( unsigned int col = line; col < noOfColumns; ++col )
{
data[line * noOfColumns + col] = backupData[col * noOfRows + line];
}
}
delete [] backupData;
return *this;
}
然后,您可以这样使用它:
matrix.Transpose(); // modifies matrix object
cout << "The transposed version = " << endl;
cout << transposed << endl;
关于c++ - 如何为我的非静态转置函数实现 matrix.Transpose()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34623979/