C++ 利用二维vector实现二维矩阵相乘(非面向对象版本)

Matrix1与Matrix2相乘,结果保存在Matrix3中

#include
#include
#include
#include
#include
#include
using namespace std;

void main()
{
    //利用vector建立二维数组

    vector<vector<int> >Matrix1(2, vector<int>(2));/
    vector<vector<int> >Matrix2(2, vector<int>(3));

    int a[2][2] = { 1,1,2,2 };
    int b[2][3] = { 2,2,2,1,1,1 };

    //赋值方法1
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            Matrix1[i][j] = a[i][j];
    //赋值方法2
    for (int i = 0; i<2; i++)
    {
        vector<int> tmp;
        for (int j = 0; j<3; j++)
        {
            tmp.push_back(b[i][j]);
        }
        copy(tmp.begin(), tmp.end(), Matrix2[i].begin());
    }
    ostream_iterator<int>os(cout, " ");
    cout << "Matrix1:" << endl;
    for (int i = 0; i < Matrix1.size(); i++)
    {
        copy(Matrix1[i].begin(), Matrix1[i].end(), os);
        cout << endl;
    }
    cout << "Matrix2:" << endl;
    for (int i = 0; i < Matrix2.size(); i++)
    {
        copy(Matrix2[i].begin(), Matrix2[i].end(), os);
        cout << endl;
    }

    vector<vector<int> >Matrix3(2, vector<int>(3));
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
        {
            Matrix3[i][j] = 0;
            for (int k = 0; k < 2; k++)
            {
                Matrix3[i][j] += Matrix1[i][k] * Matrix2[k][i];
            }
        }

    cout << "Matrix3:" << endl;
    for (int i = 0; i < Matrix3.size(); i++)
    {
        copy(Matrix3[i].begin(), Matrix3[i].end(), os);
        cout << endl;
    }
}

你可能感兴趣的:(STL)