YetiCodeCamp - C++ for Beginners

Companion website for the C++ for Beginners YouTube video series.

C++ Vector clear() Function

The C++ vector.clear() function removes (erases) the elements of the vector.


Example, using a vector “v1”.


Erases the elements of the vector v1.

This example is a complete program using the vector clear() function to remove the elements in a vector.


int main()
     std::vector<std::string> v1{"Jan","Feb","Mar","Apr","May","Jun",
     for( v : v1 )
          std::cout << v << " ";
     std::cout << "\nSize of v1 is: " << v1.size() << std::endl;


     std::cout << "\nContents of v1 after clear: " << std::endl;

     for( v : v1 )
          std::cout << v << " ";
     std::cout << "\nSize of v1 after clear is: " << v1.size() << std::endl;

return 0;

Output: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Size of v1 is: 12

Contents of v1 after clear:

Size of v1 after clear is: 0