vector::insert segmentation fault

后端 未结 3 1065
一个人的身影
一个人的身影 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-03 14:40

    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 讨论(0)
  • 2021-01-03 14:42

    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/

    0 讨论(0)
提交回复
热议问题