我正在尝试将矩阵旋转到位以进行在线编程挑战。我选择将矩阵实现为矢量矢量并执行转置并打印它。但我的问题是转置后矩阵的内容没有改变。有人可以告诉我我做错了什么吗?以下是我写的代码。提前谢谢。
#include<iostream>
#include<vector>
#include<iomanip>
// matrix dimension
int const Dim {4};
auto Fill = [] (auto& mat)
{
auto c = 1;
for(auto i=0; i<Dim; ++i)
for(auto j=0; j<Dim; ++j)
mat[i][j] = c++;
};
auto Print = [] (auto const& mat)
{
for(auto i=0; i<Dim; ++i)
{
for(auto j=0; j<Dim; ++j)
std::cout << std::setw(3) << mat[i][j];
std::cout << "\n";
}
std::cout << "\n";
};
auto Transpose = [] (auto& mat)
{
for(auto i=0; i<Dim; ++i)
for(auto j=0; j<Dim; ++j)
std::swap(mat[i][j], mat[j][i]);
};
auto main()->int
{
std::vector<std::vector<int>> mat(Dim,
std::vector<int>(Dim));
Fill(mat);
cout << "Before Transpose: \n";
Print(mat);
Transpose(mat);
cout << "After Transpose: \n";
Print(mat);
return 0;
}
==================================
Output:
Before Transpose:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
After Transpose:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16