我在矩阵类中创建了一个1d数组。打印效果很好。但是当我换位并随后打印时,它会打印出乱码。我已经检查了交换的值,它们也是应该的方式。但是当我打印时,它会打印垃圾。这是转置后的输出:
-572662307 -572662307 -572662307
-572662307 -572662307 -572662307
-572662307 -572662307 -572662307
-572662307 -572662307 -572662307
-572662307 -572662307 -572662307
我在做什么错?任何帮助将不胜感激。
inside Matrix Transpose.h file:
class Matrix{
public:
int* array;
int row, column;
std::bitset<HASH_SIZE> b;
Matrix(int r, int c) : row(r), column(c), array(new int[r * c]) {}
~Matrix() { delete[] array;}
int size() { return row * column; }
void inputMatrix();
void PrintArray();
};
void MatrixInplaceTranspose(Matrix matrix);
inside Matrix Transpose.cpp file:
void MatrixInplaceTranspose(Matrix matrix){
int r = matrix.row, c = matrix.column;
int size = r * c - 1;
int temp;
int next;
int cycleBegin;
int i;
matrix.b.reset();
matrix.b[0] = matrix.b[size] = 1;
i = 1;
while (i < size)
{
cycleBegin = i;
temp = matrix.array[i];
do
{
next = (i * r) % size;
swap(matrix.array[next], temp);
matrix.b[i] = 1;
i = next;
} while (i != cycleBegin);
for (i = 1; i < size && matrix.b[i]; i++)
;
cout << endl;
}}
inside main.cpp:
using namespace std;
void Matrix::inputMatrix(){
for (int i = 0; i < this->size(); i++)
array[i] = i + 1;
}
void Matrix::PrintArray(){
for (int r = 0; r < this->row; r++) {
for (int c = 0; c < this->column; c++)
cout << this->array[r*this->column + c] << " ";
cout<<"\n";
}
cout<<"\n\n";}
int main(void){
Matrix First(2, 5), Second(5, 3);
First.PrintArray();
Second.PrintArray();
MatrixInplaceTranspose(Second);
Second.PrintArray();
cin.get();
return 0;
}