AAA
AAA

Reputation: 448

Why std::vector resize fails?

I am trying to resize vector defined over a defined custom class

class Product{
private:
    Product *next;
    int pid;

public:
    Product(int _pid): pid(_pid){}
};

int main(){
    vector<Product> v;
    v.resize(1, Product(1));
    v[0] = Product(1);
    cout<< v.size() << endl;
    v.resize(2, Product(2));
}

My code is failing when i try to resize it second time, I have looked over other answers but I couldn't really get the idea behind it.

I have a requirement where I need to resize the vector.

Could someone please explain it and any workaround for it?

Upvotes: 0

Views: 6632

Answers (1)

ppsz
ppsz

Reputation: 342

If you want to add new Product to your vector it would be a much easier to use v.push_back(Product(1)); instead. This way you won't have to resize it by yourself.

But the answer to your question is that there is no problem with second resize, because after calling v.resize(1, Product(1));, the size of your v is 1, and it can store only one object. (As a reminder first index of every array, vector, etc. is equal to 0). Your program doesn't work because by using v[1] = Product(1); you try to access second index of your vector, and that's out of range.

If you change your main to this, the problem disappears:

int main(){
    vector<Product> v;
    v.resize(1, Product(1));
    v[0] = Product(1);
    v.resize(2, Product(2));
}

Upvotes: 7

Related Questions