我试图转置一个矩阵,如下所示。我通过引用传递数组,并且它不起作用(AFTER与BEFORE相同)。我不知道为什么。
但是,我真正感到惊讶的是,即使在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
$
答案 0 :(得分:3)
您是否可以将其转置两次:
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;
}
}
即。将src(i,j)
替换为src(j,i)
...然后将src(j,i)
替换为src(i,j)
?
答案 1 :(得分:0)
更好的优化是
for(int i = 0; i < M; i++) {
for(int j = 0; j < i; j++) { <---------------- Compare j with i and not with N
// if (i == j) continue; <---------------- No need to do this extra check
int temp = src[i][j];
src[i][j] = src[j][i];
src[j][i] = temp;
}
}