Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C++
Reference
Libraries Reference
<vector>
Classes
vector Class
Member Functions
 vector::clear
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Standard C++ Library Reference 
vector::clear 

Erases the elements of the vector.

void clear( );
// 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

Header: <vector>

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Just a tiny note on vector<...> and clear()      ElectroZap   |   Edit   |   Show History

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

Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker