简体   繁体   中英

Error when printing a 2d vector from an object

Good day! I am making a matrix class and the function which should print out a matrix breaks the program. I am pretty sure that the logic is correct, so I have probably made a silly mistake somewhere. Thing is, I can't seem to find it.

Here is the entire scource code:

#include <iostream>
#include <vector>
using namespace std;


class Matrix{
    private:

    double determinant;
   vector<vector <int> > body;
    int ROWS;
    int COLUMNS;
    public:
    int get_rows(){return ROWS;}
    int get_columns(){return COLUMNS;}
    vector<vector <int> > get_body(){return body;}
    //default constructor
    Matrix();
    //set up constructor
    Matrix(int rows, int columns);
};

//creates the matrix and let's the user fill it's value
Matrix :: Matrix(int ROWS, int COLUMNS){
     vector< vector<int> > body;
    this->ROWS = ROWS;
    this->COLUMNS = COLUMNS;
     for(int i = 0; i < ROWS; i++){
        cout<<"Row " << i << " begins" <<endl;
        vector<int> tmp;
        for(int z = 0; z < COLUMNS; z++){
            cout<<"Column "<< z<< " begins."<<endl;
            int temp;
            cin >> temp;
            tmp.push_back(temp);
        }
        body.push_back(tmp);
    }
}

//default constructor
Matrix:: Matrix(){
     vector< vector<int> > body;
}

void  print(Matrix a){
    for(int i = 0; i < a.get_rows(); i++){

        for(int z = 0; z < a.get_columns(); z++){
            cout<<a.get_body()[i][z];
        }
        cout<< endl;
    }
}
int main()
{
    Matrix a(2, 2);
    print(a);
    return 0;
}

And the body of the broken function:

void  print(Matrix a){
    for(int i = 0; i < a.get_rows(); i++){

        for(int z = 0; z < a.get_columns(); z++){
            cout<<a.get_body()[i][z];
        }
        cout<< endl;
    }
}

Your problem is, that in your constructor you work on a local variable called body instead of the class member.

Matrix :: Matrix(int ROWS, int COLUMNS){
//    vector< vector<int> > body;
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^ this should not be here!
    this->ROWS = ROWS;
    this->COLUMNS = COLUMNS;
     for(int i = 0; i < ROWS; i++){
        cout<<"Row " << i << " begins" <<endl;
        vector<int> tmp;
        for(int z = 0; z < COLUMNS; z++){
            cout<<"Column "<< z<< " begins."<<endl;
            int temp;
            cin >> temp;
            tmp.push_back(temp);
        }
        body.push_back(tmp);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM