# How to Initialize 2D Vector or an object in class

What is the correct way to initialize any object (2D vector in this case)?

Getting compilation error: " no match for ‘operator!=’ "

``````
class Solution {
public:

vector<vector<int>> *dp;

Solution(){
dp = new vector<vector<int>>(5001,vector<int>(501,-1));
}

int f(int c,int indx,const vector<int> &v){
if(c==0)return 1;
if(indx>=v.size())return 0;
if(c<0)return 0;
if(dp[c][indx]!=-1)return dp[c][indx];//ERROR HERE:  " no match for 'operator!=' "
int ans=f(c,indx+1,v)+f(c-v[indx],indx,v);
dp[c][indx]=ans;
return ans;
}

int change(int amount, vector<int>& coins) {
return f(amount,0,coins);
}
};
``````

Instead of `dp[c][indx]` use `(*dp)[c][indx]` or equivalently `dp[0][c][indx]` because `dp` is a pointer.

I would also suggest not using a pointer and omitting the `new` keyword when initializing.

1 Like
``````class Solution {
public:

vector<vector<int>> dp;

Solution(){
dp.assign(5001,vector<int>(501,-1));
}

int f(int c,int indx,const vector<int> &v){
if(c==0)return 1;
if(indx>=v.size())return 0;
if(c<0)return 0;
if(dp[c][indx]!=-1)return dp[c][indx];//ERROR HERE:  " no match for 'operator!=' "
int ans=f(c,indx+1,v)+f(c-v[indx],indx,v);
dp[c][indx]=ans;
return ans;
}

int change(int amount, vector<int>& coins) {
return f(amount,0,coins);
}
};``````
1 Like

Thanks! That helps.

One more thing:

``````class Solution {
public:
//1st one works, 2nd one gives error, why?
vector<vector<int>> dp = vector<vector<int>>(5001,vector<int>(500,-1));//works
vector<vector<int>> dp(5001,vector<int>(500,-1));
//error : "expected identifier before numeric constant vector<vector<int>> dp(5001,vector<int>(500,-1));"

};
``````

Is “dp.assign(5001,vector<int>(501,-1));” same as “dp = vector<vector>(5001,vector(500,-1));” ?

Why can’t I just assign It from the constructor while declaring?
like this: vector<vector<int>> dp(5001,vector<int>(500,-1));

No idea why that happens. Seems to be something with declaring it inside the class. I copy pasted the exact same line inside `main` and it compiles.

EDIT: I found this.
`vector<vector<int>> dp{5001,vector<int>(500,-1)};` works.

1 Like

Thanks!
What is the reason for this? Or is it just how the syntax is…?

1 Like

I think both are the same.

1 Like