Surabhi Choudhary
Surabhi Choudhary

Reputation: 548

2D Vector pointer as member of class

I am new to c++. I am trying to make a class which consist of 2d vector pointer. I am creating an object that takes a 2D vector as an argument. I am trying to reference this 2D vector using pointer.This compiles just fine, but I get a segmentation fault whilst execution. I am attaching my code here. Please do help!

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

class Vectorref {
        vector<vector<float> >  *vptr; // pointer to 2D vector

    public:
        Vectorref(vector<vector<float> >);
        double getval(int,int);
};

Vectorref::Vectorref(vector<vector<float> > v)
{
    vptr = &v;
}

double Vectorref::getval(int r, int c)
{
    return (*vptr)[r][c];
}

int main(){
    vector<vector<float> > A (3,vector<float>(3,2.0));

    Vectorref B(A);

    for(int i=0; i<3 ;i++){
        for(int j=0; j<3; j++){
            cout << B.getval(i,j) << "\t";
        }
        cout << endl;
    }

    return 0;
}

Upvotes: 1

Views: 128

Answers (1)

Jonas
Jonas

Reputation: 7017

You should pass v as a reference instead of copying.

Vectorref(vector<vector<float> >&);
Vectorref::Vectorref(vector<vector<float> >& v)

You MUST make sure that your vector<vector<float>> outlives your Vectorref, otherwise you'll get segmentation fault, again.

Your getval function should return float and not double.

Upvotes: 1

Related Questions