Ryuzaki
Ryuzaki

Reputation: 105

Simple Idea in Vectors isn't working (Compilation errors)

What is wrong with this code

vector< vector<int> > elements(lvls+1);

for(int p=1;p<=lvls;p++)
    elements[p] = new vector<int>(p+1,0);

or

vector< vector<int> > elements(lvls+1);

for(int p=1;p<=lvls;p++)
    elements[p] ( vector<int>(p+1,0) );

Both of them aren't working

While we know

vector< vector<int> > elements(lvls+1,vector<int>(lvls+1,0));

this works..

I can do this but it is not optimal as it will lead to waste of memory Kindly provide the solution

Upvotes: 0

Views: 62

Answers (2)

Jonas
Jonas

Reputation: 7017

The problem with your first attempt is that you are trying to assign a pointer to a vector of int i.e., vector<int>* to a vector<int> (not a pointer). You could simply remove the new keyword, like this:

std::vector<std::vector<int>> elements(lvls + 1);
for (int p = 1; p <= lvls; p++)
    elements[p] = std::vector<int>(p + 1, 0);

This will invoke the move assignment operator: operator=(vector&&)

Off-topic

Is there any reason why you are not using the first element (index 0) in elements?

Upvotes: 1

Marcin Zdunek
Marcin Zdunek

Reputation: 1011

You should write it that way:

vector< vector<int> > elements(lvls+1);

for(int p=0; p < lvls + 1; p++)
    elements[p].resize(p+1, 0);`

Each vector element in vector called elements is already initialized, not need to use new or constructor. I guess you only wanted to resize it, so here you are.

Upvotes: 2

Related Questions