【发布时间】:2012-01-22 20:56:22
【问题描述】:
我想为动态二维数组创建一个转置函数。我希望函数将二维数组以及行和列作为参数。我决定使用双指针。但是我对如何从 main 调用函数有点困惑。所以我得到了上面的代码
#include<iostream>
using namespace std;
void transposeMatrix(double **mat, int rows, int columns)
{
mat = new double*[rows];
for (int i = 0; i < rows; ++i)
{
mat[i] = new double[columns];
}
double temp;
for (int i = 0; i<rows; i++)
{
for (int j = i+1; j<columns; j++)
{
temp=mat[i][j];
mat[i][j]=mat[j][i];
mat[j][i]=temp;
}
}
cout<< "\n";
for (int i = 0; i<rows; i++)
{
for (int j = 0; j<columns; j++)
{
cout << mat[i][j] << " \t";
}
cout << "\n";
}
}
int main()
{
int rows = 10;
int columns = 10;
double mat[rows][columns];
for (int i = 0; i<rows; i++)
{
for (int j = 0; j<columns; j++)
{
mat[i][j] = j;
}
}
for (int i = 0; i<rows; i++)
{
for (int j = 0; j<columns; j++)
{
cout << mat[i][j] << " \t";
}
cout << "\n";
}
//mat = new double[50][1];
transposeMatrix(mat, 10, 10);
system("pause");
return 0;
}
有什么想法吗?
【问题讨论】:
-
请尝试格式化您问题中的代码。 Astyle 是一个很好的代码格式化程序的例子。还有,这是作业吗?
-
这段代码有逻辑错误。
mat = new double*[rows];将导致您丢失传入的数组。 ` -
这不是功课,实际上我想创建一个函数来为项目转置通用二维函数。转置功能正常工作。如果我将矩阵初始化放在函数内,它会返回所需的结果。但我不知道怎么称呼它。
-
嗯,这段代码原地转置矩阵。仅当矩阵为正方形时才有效,因此行 = 列。
标签: c++ dynamic matrix transpose