jeudi 30 juillet 2020

Passing data from constructor to member function

I am trying to write a class that do matrix multiplication. The class matrix declared like below:

class matrix
{
public:
    vector<vector<int> > M;

    matrix();
    matrix(int m, int n);
    matrix(vector<vector<int> > &m);
    matrix Mul(matrix m1);
    void Inverse();
    bool SquareMatrix();
    void GetDet();
    int Det(vector<vector<int> > &m);
    void Print();
};

I initialize and enter the elements of the matrix M in this constructor:

matrix::matrix(int m, int n)
{
    vector<vector<int> > M(m, vector<int>(n, 0));
    cout << "Enter the elements: " << endl;

    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cin >> M[i][j];
        }
    }
}

However, the member function "Mul" do not receive the data I input through the constructor.

matrix matrix::Mul(matrix m1)
{
    int **ppInt;
    ppInt = new int *[M.size()];
    for (int i = 0; i < M.size(); i++)
    {
        ppInt[i] = new int[m1.M[0].size()];
    }

    if (M[0].size() != m1.M.size())
    {
        cout << "Cannot do multiplication!" << endl;
        return matrix();
    }
    else
    {
        for (int i = 0; i < M.size(); i++)
        {
            for (int j = 0; j < m1.M[0].size(); j++)
            {
                int ele_buf = 0;
                for (int k = 0; k < M[0].size(); k++)
                {
                    ele_buf += M[i][k] * m1.M[k][j];
                }
                ppInt[i][j] = ele_buf;
            }
        }
    }
    int d1 = M.size(), d2 = m1.M[0].size();

    for (int i = 0; i < M.size(); i++)
    {
        M[i].clear();
    }
    M.clear();

    for (int i = 0; i < d1; i++)
    {
        for (int j = 0; j < d2; j++)
        {
            M[i][j] = ppInt[i][j];
        }
    }
}

How can I fix it?

Please let me know if my problem is not clear enough.

Aucun commentaire:

Enregistrer un commentaire