转置矩阵:交换元素不会改变值 [英] Transpose matrix: swapping elements doesn't alter values
本文介绍了转置矩阵:交换元素不会改变值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试转置由向量构建的矩阵.
I am trying to transpose a matrix built with vectors.
这是我写的转置函数:
void transpose(std::vector<std::vector<int>>& fill_mat) {
for (int i = 0; i < fill_mat.size(); ++i) {
for (int j = 0; j < fill_mat.size(); ++j) {
std::swap(fill_mat[i][j], fill_mat[j][i]);
}
}
}
似乎什么也没做:我的最终结果与开始的结果相同.
It doesn't seem to be doing anything: my final results are the same as the starting ones.
这是我的完整程序:
#include<iostream>
#include<vector>
#include<utility>
void print_matrix(std::vector<std::vector<int>>& to_print) {
for (int i = 0; i < to_print.size(); ++i) {
for (int j = 0; j < to_print.size(); ++j) {
std::cout << " " << to_print[i][j];
}
std::cout << std::endl;
}
}
void make_matrix(std::vector<std::vector<int>>& fill_mat) {
for (int i = 0; i < fill_mat.size(); ++i) {
for (int j = 0; j < fill_mat.size(); ++j) {
fill_mat[i][j] = rand() % 15;
}
}
}
void transpose(std::vector<std::vector<int>>& fill_mat) {
for (int i = 0; i < fill_mat.size(); ++i) {
for (int j = 0; j < fill_mat.size(); ++j) {
std::swap(fill_mat[i][j], fill_mat[j][i]);
}
}
}
int main() {
int size = 3;
std::vector<std::vector<int>> matrix_sample(size, std::vector<int>(size));
make_matrix(matrix_sample);
print_matrix(matrix_sample);
transpose(matrix_sample);
std::cout << "----## transpose ##-----" << std::endl;
print_matrix(matrix_sample);
}
我希望打印出转置矩阵,但是输入最终与输出相同.我在做什么错了?
I expected to print out the transposed matrix but the input ends up being the same as the output. What am I doing wrong?
推荐答案
您将(i,j)与(j,i)交换了两次!这就是为什么它无效的原因.
You swap (i,j) with (j,i) twice! That's why it has no effect.
您应该只处理矩阵的一半.加上未成年人的改善,我们得到:
You should only work on one half of your matrix. Plus minors improvements, we get:
void transpose(std::vector<std::vector<int>>& fill_mat)
{
using size_type = decltype(fill_mat)::size_type; // better use your matrix' size type
for (size_type i = 0; i < fill_mat.size(); ++i) {
for (size_type j = 0; j < i; ++j) {
using std::swap; // see swap idiom
swap(fill_mat[i][j], fill_mat[j][i]);
}
}
}
这篇关于转置矩阵:交换元素不会改变值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文