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

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

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

but it doesn't work.


Update: Doesn't clear destruct the elements held by the vector? I don't want that, as I'm still using the objects, I just want to empty the container

This question is related to c++ stl vector

The answer is


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);

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;
}

vector.clear() is effectively the same as vector.erase( vector.begin(), vector.end() ).

If your problem is about calling delete for each pointer contained in your vector, try this:

#include <algorithm>

template< typename T >
struct delete_pointer_element
{
    void operator()( T element ) const
    {
        delete element;
    }
};

// ...
std::for_each( vector.begin(), vector.end(), delete_pointer_element<int*>() );

Edit: Code rendered obsolete by C++11 range-for.


If your vector look like this std::vector<MyClass*> vecType_pt you have to explicitly release memory ,Or if your vector look like : std::vector<MyClass> vecType_obj , constructor will be called by vector.Please execute example given below , and understand the difference :

  class MyClass
    {
    public:
        MyClass()
        {
            cout<<"MyClass"<<endl;
        }
        ~MyClass()
        {
            cout<<"~MyClass"<<endl;
        }
    };
    int main() 
    {
        typedef std::vector<MyClass*> vecType_ptr;
        typedef std::vector<MyClass> vecType_obj;
        vecType_ptr myVec_ptr;
        vecType_obj myVec_obj;
        MyClass obj;
        for(int i=0;i<5;i++)
        {
            MyClass *ptr=new MyClass();
            myVec_ptr.push_back(ptr);
            myVec_obj.push_back(obj);
        }
        cout<<"\n\n---------------------If pointer stored---------------------"<<endl;
        myVec_ptr.erase (myVec_ptr.begin(),myVec_ptr.end());
        cout<<"\n\n---------------------If object stored---------------------"<<endl;
        myVec_obj.erase (myVec_obj.begin(),myVec_obj.end());
        return 0;
    }

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


Adding to the above mentioned benefits of swap(). That clear() does not guarantee deallocation of memory. You can use swap() as follows:

std::vector<T>().swap(myvector);

Use v.clear() to empty the vector.

If your vector contains pointers, clear calls the destructor for the object but does not delete the memory referenced by the pointer.

vector<SomeClass*> v(0);

v.push_back( new SomeClass("one") );

v.clear();  //Memory leak where "one" instance of SomeClass is lost

class Class;
std::vector<Class*> vec = some_data;

for (unsigned int i=vec.size(); i>0;) {
    --i;
    delete vec[i];
    vec.pop_back();
}
// Free memory, efficient for large sized vector
vec.shrink_to_fit();

Performance: theta(n)

If pure objects (not recommended for large data types, then just vec.clear();


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to stl

Why is it OK to return a 'vector' from a function? How to remove all the occurrences of a char in c++ string How to use the priority queue STL for objects? use std::fill to populate vector with increasing numbers What does iterator->second mean? How to set initial size of std::vector? Sorting a vector in descending order How do I reverse a C++ vector? Recommended way to insert elements into map Replace an element into a specific position of a vector

Examples related to vector

How to plot vectors in python using matplotlib How can I get the size of an std::vector as an int? Convert Mat to Array/Vector in OpenCV Are vectors passed to functions by value or by reference in C++ Why is it OK to return a 'vector' from a function? Append value to empty vector in R? How to initialize a vector with fixed length in R How to initialize a vector of vectors on a struct? numpy matrix vector multiplication Using atan2 to find angle between two vectors