I am trying to transpose a matrix, like below. I am passing the array by reference, and somehow it is not working (AFTER is same as BEFORE). I am not sure why.
But, What I am really surprised about is that the array is not transposed even inside the transpose() function (how can INSIDE be the same as BEFORE??). What am I missing?
#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);
}
Output:
$ ./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
$
Are you maybe transposing it twice:
i.e. substitute
src(i,j)forsrc(j,i)… and then substitutesrc(j,i)forsrc(i,j)?