修改函数内的多维数组
Modifying a Multi-dimensional Array inside a function
我有一个作业,只能使用数组索引来查找矩阵的转置(在 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, j
与j, i
交换,并确保以后不要单独j, i
与i, 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 及更高版本)添加包含。
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值