用STL编写矩阵就地顺时针旋转90°
时间: 2023-09-02 16:14:46 浏览: 167
可以使用C++的STL库中的vector来表示矩阵,然后就地顺时针旋转90度可以通过以下步骤实现:
1. 先将矩阵沿着主对角线交换元素;
2. 然后将每行的元素翻转,即第一列和最后一列交换,第二列和倒数第二列交换,以此类推。
以下是代码实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
// 沿主对角线交换元素
for(int i=0; i<n; i++) {
for(int j=0; j<i; j++) {
swap(matrix[i][j], matrix[j][i]);
}
}
// 每行翻转
for(int i=0; i<n; i++) {
for(int j=0; j<n/2; j++) {
swap(matrix[i][j], matrix[i][n-j-1]);
}
}
}
int main() {
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);
for(int i=0; i<matrix.size(); i++) {
for(int j=0; j<matrix[i].size(); j++) {
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
```
输出结果为:
```
7 4 1
8 5 2
9 6 3
```
阅读全文
相关推荐
















