开发者

vector::insert segmentation fault

I have a class like this:

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

   }

   void updateVec(int idx, int value)
   {
     //Here, I want to update vector vector based on args passed
     myVec.insert(myVec.begin() 开发者_运维知识库+ idx, value);

   }

  std::vector<int> myVec;
}

Now, I am getting segmentation fault on insert statement. Do I need to initialize vector somewhere?


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.


From your code it seems that you did not initialize it properly.

initialization for use as local var
Create a vector of ints, size 3, initialized to 0

std::vector<int> myvector (3,0);

Short example of how to initialize(and then resize) a vector in a class's constructor

#include <iostream>
#include <vector>

class A {
public:
   A(int size);
   ~A();
   void updateVec(int idx, int value);
   void print();
private:
  std::vector<int> myVec;
};

A::A(int size) {
    myVec.resize(size);
}

A::~A() {
}

void A::updateVec(int idx, int value) {
     myVec.insert(myVec.begin() + idx, value);
}

void A::print() {
    std::vector<int>::iterator it;
    for (it=myVec.begin(); it!=myVec.end(); it++) {
        std::cout << " " << *it;
    }
}

int main() {
    A* a = new A(10);
    a->updateVec(2,10);
    a->print();
}

Here is documentation/example on how to use a vector in C++
http://www.cplusplus.com/reference/stl/vector/insert/


Yes, you do. Vectors start off empty. Any attempt to access an item past the end of the vector will result in an error.

To suggest a solution we'll need to know if the vector needs to change size dynamically - or if it is a fixed size, at what point in time will you know what size it needs to be.

Also, if you update the 17th elemnt of the vector, but at the time it only contains 10 items, do you want items 11 to 16 to be created as well?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜