vector::insert segmentation fault

后端 未结 3 1066
一个人的身影
一个人的身影 2021-01-03 13:46

I have a class like this:

classA
{
public:
  classA()
   {
     //Here I am doing something but nothing related to vector

   }

   void updateVec(int idx, i         


        
3条回答
  •  -上瘾入骨i
    2021-01-03 14:32

    Segmentation fault means you're trying to access/write into memory that has not (yet) been allocated. In your case, depending on value of idx, myVec.begin() + idx can refer to memory that is out of vector's allocated zone. Before inserting, you need to make sure your vector can hold at least idx elements. updateVec should check the current size of the vector, and if it is not big enough, it should call vector::reserve to allocate enough room so new element can be inserted.

提交回复
热议问题