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.
Note that your for loops are different. This is why passing by value gives correct answer. Delete line 27 and see for yourself that it does nothing (when you pass by value).
I'm not sure what your transpose function is doing (it looks complicated)..