vector::clear function


The clear function erases all the elements in the vector.

void clear( ) ;

In calling this function all the elements of the vector are erased thereby reducing the size of the vector to 0.The capacity of the vector however remains the same.

Parameters:
none – The function does not accept any parameter.

Return type
void – The function does not return any type.

Code example

vector<string >vec = { “Vector” , ” to” , ” hold string” } ;

cout << “Capacity=” << vec.capacity( ) << endl ;

for( auto elem : vec )
{
cout << elem ;
}

vec.clear( ) ;

//cout << vec[0] ; //undefined

cout << “\nSize=” << vec.size( ) << endl;
cout << “Capacity=” << vec.capacity( ) ;

Output,

Capacity=3
Vector to hold string
Size=0
Capacity=3

If you want to empty your vector in an instant use this function.





Precaution to take while using clear()

If the vector holds pointers that point to some dynamic memory ,then calling the clear() function will only erase the pointer itself not the memory pointed by them.The responsibility of freeing the storage falls in the hand of the user.

Code example

string *st = new string(“New”) , *st1 = new string(” string”) ;

vector<string *> vecSt = { st , st1 } ;

cout << vecSt[0] << vecSt[1] << endl ;

vecSt.clear( ) ;

//accessing the data in the dynamic storage after calling clear
cout << *st << *st1 << endl ;

delete st ; //do not forget
delete st1 ; //do not forget

Output,

New string

Forgetting to delete the storage before the program termination can lead to memory leakage.If you want to make sure that the storage is taken care of without needing to call the ‘delete operator‘ explicitly for each pointer then you should consider using smart pointer.An example is shown below where a vector stores the smart pointer:shared_ptr ,instead of the normal raw pointer and you will see that the smart pointer will take care of the storage for us automatically.

Note include <memory> to use the smart pointer.

{
shared_ptr< int> sp1(new int(89)), sp2(new int(34) );

vector<shared_ptr<int>> vecSpt = { sp1 , sp2 };

//accessing the data of vecSpt
for (auto elem : vecSpt)
{
cout << *elem << ” , ” ;
}

vecSpt.clear() ;

} ///sp1 and sp2 goes out of scope here ,the storage is deleted

cout<< *sp1 << endl ///undefined
<< *sp2 ; //undefined

Output,

89 , 34

There is no need to call any ‘delete operator‘ here to delete the storage.


 


Stop wasting time,earn money($$$) from your website-Join Now!