矩阵的转置

其实矩阵的转置算法是比较容易理解的,我之所以写本文,是想提醒自己C++中的STL库使用起来真是方便极了。

代码如下:

#include <vector>
#include <algorithm>
#include <iostream>
using std::vector;
using std::for_each;
using std::cout;
using std::endl;

void OutNum(int num)
{
    cout << num << " ";
}

void OutNumSeq(const vector<int> & vecNum)
{
    for_each(vecNum.begin(), vecNum.end(), OutNum);
    cout << endl;
}

void Zhuanzhi(vector<vector<int> > & vecB, const vector<vector<int> > & vecA)
{
    int I = vecA.size();
    
    if (I <= 0 )
        return;
    
    int J = vecA[0].size();
    
    vecB.assign(J, vector<int>(I, 0));

    for (int i=0; i<I; ++i) {
        for (int j=0; j<J; ++j) {
            vecB[j][i] = vecA[i][j];
        }
    }
}

int main(int argc, char ** argv)
{
    vector<vector<int> > vecA = { {0, 1, 2, 3}, {4, 5, 6, 7} };
    vector<vector<int> > vecB;

    cout << "A:" << endl;
    for_each(vecA.begin(), vecA.end(), OutNumSeq);

    Zhuanzhi(vecB, vecA);

    cout << "B:" << endl;
    for_each(vecB.begin(), vecB.end(), OutNumSeq);

    return 0;
}

输出:

输出.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容