Sparse matrix Constructor doesn't store parameter in object

119 Views Asked by At

I want store a sparse matrix read from a file, but when the constructor finishes the parameters aren't stored in the object.

The file has a "row col" structure, where row is the matrix row and col is the matrix column. If the coordinate of the file exists, it stores a 1 in this position, otherwise it stores a 0.

This is the constructor:

MatriuSparse::MatriuSparse(const string nomFitxer) {
        fstream fitxer;
        fitxer.open(nomFitxer);

        int m_columna;
        int m_fila;
        m_Ncolumnes = 8;
        m_Nlinies = 8;
        vector<vector<int> > matriu;
        for (int i = 0; i < m_Nlinies; i++)
        {
            vector<int> temporal;
            for (int j = 0; j < m_Ncolumnes; j++) {
                temporal.push_back(0);
            }
            matriu.push_back(temporal);
        }
        fitxer >> m_fila >> m_columna;

        while (!fitxer.eof())
        {
            matriu[m_fila][m_columna] = 1;
            fitxer >> m_fila >> m_columna;
        }
        fitxer.close();
        //Here matrix has size 8
    }

And this is the main:

 string nomFitxer = "Xarxa1.txt";
    MatriuSparse m1(nomFitxer);
    // Here m1 matrix has size 0
    cout << m1;
2

There are 2 best solutions below

0
On BEST ANSWER

Your constructor doesn't store anything in the class, except m_Ncolumnes and m_Nlinies that you set to a constant value. Everything else is stored in variables that are local to the constructor and that disappear once the constructor is finished.

It is highly probable that you hide a member vector with the same name. Just remove this line:

    vector<vector<int> > matriu;   // hiding the member matriu ? 

Not related 1: you can easily initialize your vector without a nested loop:

    matriu = vector<vector<int>>(m_Nlinies, vector<int>(m_Ncolumnes, 0));

Not related 2: looping on eof() doesn't work properly. You have to loop on the extraction. So once your matriu initialized, just do:

    while (fitxer >> m_fila >> m_columna)
    {
        matriu[m_fila][m_columna] = 1;
    }
3
On

Your main problem is that you need to make matriu a member of the class, not declare it locally in the function.

In addition I have some more comments.

If you know in advance that the size of the matrix is 8x8, it is an overkill to use vector, use array.

The naming convention is a bit strange. I assume you use m_ to denote member variables, but m_columna and m_fila are local variables.

You mention a sparse matrix, but the matrix you are populating matriu is in dense format.