void TransposeMatrix (vector<int> &matrix, int N, int M)
{
assert ( N != M );
for(int i = 0; i < N*M - 1; i++)
{
int oldPos = i ;
int newPos = (N*oldPos) % (N*M - 1);
while ( newPos != i ) {
matrix [newPos] = matrix [oldPos];
oldPos = newPos;
newPos = (N*oldPos) % (N*M - 1);
}
matrix [i] = matrix [oldPos];
}
}
int main()
{
int row, col ;
cin >> row >> col ;
vector <int> A (row * col);
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
cin >> A [i*col + j] ;
TransposeMatrix (A, row, col);
for(int i = 0; i < col; i++) {
for(int j = 0; j < row; j++)
cout << setw(3) << A [i*row + j] << " ";
cout << endl;
}
return 0;
}
In this program, the function is modifying the content of vector<int> &matrix. Hence, I need to pass a reference. However, the program gives bizarre output. You can see the program output here : http://ideone.com/ct28w
The surprising fact is that when I pass the matrix as value, it shows correct output. You can see the program output here : http://ideone.com/a3UkO
Btw, this is not any homework problem. So, please help me with your suggestions. Thanks in advance.