Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ vector::clear function is used to clear all elements of the vector. This function makes the vector empty with a size of zero.

Syntax

void clear();
void clear() noexcept;

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the below example, the vector::clear function is used to clear all elements of the vector called MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};
  vector<int>::iterator it;

  cout<<"Before clear() function: \nMyVector is:";
  for(it = MyVector.begin(); it != MyVector.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nMyVector size is: "<<MyVector.size()<<"\n\n";

  MyVector.clear();

  cout<<"After clear() function: \nMyVector is:";
  for(it = MyVector.begin(); it != MyVector.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nMyVector size is: "<<MyVector.size()<<"\n\n";
  
  return 0;
}

The output of the above code will be:

Before clear() function: 
MyVector is: 10 20 30 40 50
MyVector size is: 5

After clear() function: 
MyVector is:
MyVector size is: 0

❮ C++ - Vector