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

后端 未结 9 1235
陌清茗
陌清茗 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:22

    Is v.clear() not working for some reason?

    0 讨论(0)
  • 2020-12-04 10:24

    vector.clear() should work for you. In case you want to shrink the capacity of the vector along with clear then

    std::vector<T>(v).swap(v);
    
    0 讨论(0)
  • 2020-12-04 10:26

    If you keep pointers in container and don't want to bother with manually destroying of them, then use boost shared_ptr. Here is sample for std::vector, but you can use it for any other STL container (set, map, queue, ...)

    #include <iostream>
    #include <vector>
    #include <boost/shared_ptr.hpp>
    
    struct foo
    {
        foo( const int i_x ) : d_x( i_x )
        {
            std::cout << "foo::foo " << d_x << std::endl;
        }
    
        ~foo()
        {
            std::cout << "foo::~foo " << d_x << std::endl;
        }
    
        int d_x;
    };
    
    typedef boost::shared_ptr< foo > smart_foo_t;
    
    int main()
    {
        std::vector< smart_foo_t > foos;
        for ( int i = 0; i < 10; ++i )
        {
            smart_foo_t f( new foo( i ) );
            foos.push_back( f );
        }
    
        foos.clear();
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题