Search code examples
c++classsparse-matrixadjacency-matrix2d-vector

Sparse matrix Constructor doesn't store parameter in object


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;

Solution

  • 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;
        }