Transpose matrix: swapping elements doesn't alter values

后端 未结 1 326
我在风中等你
我在风中等你 2021-01-23 16:39

I am trying to transpose a matrix built with vectors.

Here is the transpose function I wrote:

void transpose(std::vector>&am         


        
相关标签:
1条回答
  • 2021-01-23 17:32

    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]);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题