修改函数内的多维数组

Modifying a Multi-dimensional Array inside a function

本文关键字:数组 函数 修改      更新时间:2023-10-16

我有一个作业,只能使用数组索引来查找矩阵的转置(在 c++ 中)。 我的 main 调用函数 indexTranspose,但我无法弄清楚为什么当我在函数内打印数组时输出是正确的,但是当我在主函数中打印出来时,矩阵没有更新。 矩阵是一个充满 9 个随机整数的文本文件。

#include <iostream>
#include <fstream>
using namespace std;
//function declarations
void printMatrix(int m[][3]);
void indexTranspose(int n[3][3]);
//void pointerTranspose(int m[][3]);
//begin main
int main() {
int m[3][3];
ifstream values("matrix.txt");
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
values >> m[i][j];
printMatrix(m);
indexTranspose(m);
printMatrix(m);
/*pointerTranspose(m);
printMatrix(m);
*/
} //end main
void printMatrix(int m[][3]) {
for (int i = 0; i < 3; i++) {
cout << "[ ";
for (int j = 0; j < 3; j++)
cout << m[i][j] << " "; 
cout << "]" << endl;
}
cout <<endl;
}
void indexTranspose (int n[][3]) { 
cout << "Transposing the matrix using indices..." <<endl;
int temp[3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
temp[j][i] = n[i][j];
}
n = temp;
cout << "Printing n"<< endl;
printMatrix(n);
}

运行此函数时,我得到的输出是原始矩阵,然后是转置(在函数内打印出来),然后是原始矩阵。 我不确定为什么转置函数只在本地更新数组而不是在 main 中修改数组。

您不应该尝试在indexTranspose函数中重新分配n。相反,交换数组中的各个值。 将i, jj, i交换,并确保以后不要单独j, ii, j交换。

void indexTranspose (int n[][3])
{ 
std::cout << "Transposing the matrix using indices..." << std::endl;
for (int i = 0; i < 3; i++)
{
// the j < i ensures, that i, j are not swapped twice and i, i is never swapped because its the same index anyway
for (int j = 0; j < i; j++)
{
std::swap(n[i][j], n[j][i]);
}
}
std::cout << "Printing n"<< std::endl;
printMatrix(n);
}

要使用std::swap,请为<algorithm>(C++98) 或<utility>(C++11 及更高版本)添加包含。