简体   繁体   English

为什么std :: vector调整大小失败?

[英]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? 有人可以解释一下,以及任何解决方法吗?

If you want to add new Product to your vector it would be a much easier to use v.push_back(Product(1)); 如果要向vector添加新Product ,则使用v.push_back(Product(1));会容易得多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)); 但是,您的问题的答案是第二次调整大小没有问题,因为在调用v.resize(1, Product(1)); , the size of your v is 1 , and it can store only one object. v的大小为1 ,并且只能存储一个对象。 (As a reminder first index of every array , vector , etc. is equal to 0 ). (提醒一下,每个arrayvector等的第一个索引等于0 )。 Your program doesn't work because by using v[1] = Product(1); 您的程序无法正常工作,因为使用v[1] = Product(1); you try to access second index of your vector , and that's out of range. 您尝试访问vector第二个索引,但超出范围。

If you change your main to this, the problem disappears: 如果您将main更改为此,问题将消失:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM