Delete all items from a c++ std::vector

后端 未结 9 1278
陌清茗
陌清茗 2020-12-04 09:42

I\'m trying to delete everything from a std::vector by using the following code

vector.erase( vector.begin(), vector.end() );

9条回答
  •  日久生厌
    2020-12-04 10:06

    I think you should use std::vector::clear:

    vec.clear();
    

    EDIT:

    Doesn't clear destruct the elements held by the vector?

    Yes it does. It calls the destructor of every element in the vector before returning the memory. That depends on what "elements" you are storing in the vector. In the following example, I am storing the objects them selves inside the vector:

    class myclass
    {
    public:
        ~myclass()
        {
    
        }
    ...
    };
    
    std::vector myvector;
    ...
    myvector.clear(); // calling clear will do the following:
    // 1) invoke the deconstrutor for every myclass
    // 2) size == 0 (the vector contained the actual objects).
    

    If you want to share objects between different containers for example, you could store pointers to them. In this case, when clear is called, only pointers memory is released, the actual objects are not touched:

    std::vector myvector;
    ...
    myvector.clear(); // calling clear will do:
    // 1) ---------------
    // 2) size == 0 (the vector contained "pointers" not the actual objects).
    

    For the question in the comment, I think getVector() is defined like this:

    std::vector getVector();
    

    Maybe you want to return a reference:

    // vector.getVector().clear() clears m_vector in this case
    std::vector& getVector(); 
    

提交回复
热议问题