我在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(第4列,第3行,第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时会给新的信息(即将列和行数组切换)给矩阵对象。转换但它还没有工作。
这是正确的格式Matrix&amp; Matrix :: Transpose()用于实现matrix.Transpose()?
答案 0 :(得分:2)
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;