我正在尝试转置矩阵,如下所示。我通过引用传递数组,但不知何故它不起作用(之后与之前相同)。我不确定为什么。
但是,我真正感到惊讶的是,即使在transpose()
函数内部,数组也没有转置(INSIDE 怎么能和 BEFORE 一样??)。我错过了什么?
#include <iostream>
template <int M, int N>
void print1(int (&src)[M][N]) {
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++)
printf("%2d\t", src[i][j]);
std::cout << std::endl;
}
}
template <int M, int N>
void transpose(int (&src)[M][N]) {
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
if (i == j) continue;
int temp = src[i][j];
src[i][j] = src[j][i];
src[j][i] = temp;
}
}
std::cout << "\nINSIDE:\n";
print1(src);
}
int main() {
int src[][4] = {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16},
};
std::cout << "BEFORE:\n";
print1(src);
transpose(src);
std::cout << "\nAFTER:\n";
print1(src);
}
输出:
$ ./a.out
BEFORE:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
INSIDE:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
AFTER:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
$