Standard C++ Library Reference 
vector::clear 

Erases the elements of the vector.

void clear( );
Example

// vector_clear.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>

int main( )
{
   using namespace std;   
   vector <int> v1;
   
   v1.push_back( 10 );
   v1.push_back( 20 );
   v1.push_back( 30 );

   cout << "The size of v1 is " << v1.size( ) << endl;
   v1.clear( );
   cout << "The size of v1 after clearing is " << v1.size( ) << endl;
}

Output

The size of v1 is 3
The size of v1 after clearing is 0
Requirements

Header: <vector>

See Also

Reference

vector Class
Standard Template Library

Other Resources

vector Members

Tags :


Community Content

ElectroZap
Just a tiny note on vector<...> and clear()

Above ain't suitable if you store pointers in a vector. In this case you have to de-allocate each stored element explicitly (delete...).

You can test with the following:

#include <iostream>
#include <vector>
using namespace std;

static int k;

class A
{
public:
A() { cout << "A's " << (id=k++) << " constructor" << endl; };
~A() { cout << "A's " << (id) << " destructor" << endl; };
private:
int id;
};

int main()
{
vector<A*> vec1;
A* a;

//Test begins - store 3 pointer to a class type A
a = new A();
vec1.push_back(a);
a = new A();
vec1.push_back(a);
a = new A();
vec1.push_back(a);

cout << "\n**vec1 contains " << vec1.size() << " elements." << endl;

if(!vec1.empty())
{
for(int i=0; i<(int)vec1.size(); i++)
delete vec1[i];

vec1.clear(); //
}

cout << "\n**vec1 contains " << vec1.size() << " elements." << endl;

return 0;
}


Page view tracker