使用 C++ 中的向量转置 2D 矩阵 [英] Transpose of a 2D matrix using vectors in C++

查看:81
本文介绍了使用 C++ 中的向量转置 2D 矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用向量找出二维矩阵的转置.以下代码对我不起作用.我试图将矩阵传递给一个名为 transpose() 的函数.我还有哪些其他方法可以做到?如果您指出我的错误,我将不胜感激.

I am trying to find out the transpose of a 2D matrix using vectors. The following code is not working for me. I am trying to pass the matrix into a function named transpose(). What are the other ways I can do it? I appreciate if you point out my errors.

#include <iostream>
#include <vector>
using namespace std;

void transpose(vector<vector<int> > &b)
{
    vector<vector<int> > trans_vec;

    for(int i=0;i<b.size();i++)
    {
        for(int j=0;j<b[i].size();j++)
        {
            trans_vec[j][i]=b[i][j];
        }
    }
}

int main()
{
    vector<vector<int> > v1;
    for(int i=0;i<2;i++)
    {
        vector<int> temp;
        for(int j=0;j<3;j++)
        {
            temp.push_back(i);
        }
        v1.push_back(temp);
    }
    //Display output
    for(int i=0;i<v1.size();i++)
    {
        for(int j=0;j<v1[i].size();j++)
        {
            cout<<v1[i][j];
        }
        cout<<endl;
    }
    transpose(v1);
    //display transposed matrix
    for(int i=0;i<v1.size();i++)
    {
        for(int j=0;j<v1[i].size();j++)
        {
            cout<<v1[i][j];
        }
        cout<<endl;
    }
    return 0;
}

推荐答案

您将保持传入的参数不变.这就是为什么你看不到任何变化.此外,您正在访问无效索引,因此请使用正确的大小初始化向量.试试这个:

You are leaving the passed in parameter untouched. That's why you see no change. Also, you're accessing invalid indices, so initialize the vector with the right size. Try this:

void transpose(vector<vector<int> > &b)
{
    if (b.size() == 0)
        return;

    vector<vector<int> > trans_vec(b[0].size(), vector<int>());

    for (int i = 0; i < b.size(); i++)
    {
        for (int j = 0; j < b[i].size(); j++)
        {
            trans_vec[j].push_back(b[i][j]);
        }
    }

    b = trans_vec;    // <--- reassign here
}

这会将第一行中的向量初始化为正确的大小.当然这只有效,如果 b[0].size() == b[1].size() == ... == b[n].size().

This initializes the vector to the right size in the first line. Of course this only works, if b[0].size() == b[1].size() == ... == b[n].size().

如果你不想使用 push_back 你可以这样写:

If you don't want to use push_back you could write:

    for (int j = 0; j < b[i].size(); j++)
    {
        if (trans_vec[j].size() != b.size())
            trans_vec[j].resize(b.size());
        trans_vec[j][i] = b[i][j];
    }

另一种返回结果的方法是在函数末尾返回 trans_vec 并传入 b 作为常量引用:

Another way to return the result would be to return trans_vec at the end of the function and pass in b as a const reference:

vector<vector<int> > transpose(const vector<vector<int> > &b)
{
     ...
     return trans_vec;
}

这篇关于使用 C++ 中的向量转置 2D 矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆