Stefan1993
Stefan1993

Reputation: 303

Declare and access 2D-vector initiated in constructor c++

I have a class declared in a header file, where I have the following 2D vector:

std::vector< std::vector<int> > inputPatterns;

Then in the constructor of this class in my .cpp file, I do the following:

nInputPatterns = 4;
vector< vector<int> > inputPatterns(nInputPatterns, vector<int>(2));

inputPatterns[0][0] = 1;
inputPatterns[0][1] = 1;
inputPatterns[1][0] = 0;
inputPatterns[1][1] = 1;
inputPatterns[2][0] = 1;
inputPatterns[2][1] = 0;
inputPatterns[3][0] = 0;
inputPatterns[3][1] = 0;

However, now member function of this class can't access this 2D vector. I think that it is because I redeclare it in the constructor, but I don't know how to do it otherwise.

So my question is, how to properly declare the 2D vector in the header class and then initialise it in the .cpp file (either in the constructor or a member function) such that I can access it everywhere?

Upvotes: 0

Views: 629

Answers (2)

Stefan1993
Stefan1993

Reputation: 303

The answer to my problem seems to be to use inputPatterns.assign(nInputPatterns, vector(2)); So not this->. Can anybody explain me why?

Upvotes: 0

Khalil Khalaf
Khalil Khalaf

Reputation: 9407

You are declaring a new local variable, populating it, and then will die once the control goes out of the constructors scope. Therefore, you did not actually populate the member variable of the object, you populated an other variable that died by the time the constructor finished executing.

What you would need to do is to use the existing member variable of the class instead, and the best way for improving the code and make it more readable / understandable is to use the this pointer like here:

nInputPatterns = 4;

// means not any inputPatterns, it is explicitly the member variable inputPatterns of "this" current object / instance
this->inputPatterns(nInputPatterns, vector<int>(2)); 

// ..

Upvotes: 2

Related Questions