用STL编写矩阵就地转置
时间: 2023-09-02 13:14:46 浏览: 159
C和C++实现稀疏矩阵创建、快速转置(数据结构)
5星 · 资源好评率100%
可以使用STL中的vector来表示矩阵,然后再对其进行就地转置。以下是示例代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
void transpose(vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < m; j++) {
swap(matrix[i][j], matrix[j][i]);
}
}
}
int main() {
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
cout << "Original matrix:" << endl;
for(auto row: matrix) {
for(auto val: row) {
cout << val << " ";
}
cout << endl;
}
transpose(matrix);
cout << "Transposed matrix:" << endl;
for(auto row: matrix) {
for(auto val: row) {
cout << val << " ";
}
cout << endl;
}
return 0;
}
```
运行结果:
```
Original matrix:
1 2 3
4 5 6
7 8 9
Transposed matrix:
1 4 7
2 5 8
3 6 9
```
阅读全文