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

后端 未结 9 1283
陌清茗
陌清茗 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: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 
    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题