clear

Syntax:

    #include <vector>
    void clear();

The function clear() deletes all the elements stored in the vector. If the elements of the vector are objects, the member function 'clear()' will call the corresponding destructor of each element stored in the vector. However, if the elements of the vector are pointers to objects, this function will not call the corresponding destructors. In this second scenario, to completely delete all the elements from the vector, a loop similar to the following one should be provided:

    std::vector<SomeObject*> aVector;
    [...]  //The elements of the vector are created with the operand 'new' at some point in the program
    for(int i=0 ; i<aVector.size() ; i++)
        delete aVector[i];
    aVector.clear();

After a call to clear, the vector's new size will be zero. The vector's capacity however, will not be changed, and the vector will not release its allocated memory.

If you want to empty a vector of all of its elements, as well as its capacity, then you can use the swap trick (this trick does not work with all environments e.g. not with Intel Compiler 10.0.69 and LINUX 2.6.9-89 x64):

    std::vector aVector;
    [...]
    aVector.swap( std::vector() );

This will create a new temporary empty vector, which will swap with the vector you wish to empty.

clear() runs in linear time.

Related Topics: erase swap