What is std::vector::clear() in C++?

Vectors are useful data structures that act like dynamic one-dimensional arrays.

The clear() function is defined in the <vector> library. It is used to delete all the elements in a vector. When the vector is empty, its size becomes zero.

Syntax

myVec.clear()

Parameters

This function takes no parameters.

Return value

The function returns nothing.

The changes are made directly to the vector.

Example

#include <iostream>
#include <vector> // first include <vector>
using namespace std;
int main()
{
//declaration of int vector
vector<int> vec = {1, 2, 3, 4, 5};
// returns length of vector as unsigned int
unsigned int vecSize = vec.size();
cout << "Before using clear(), size of vector: " << vecSize << endl;
// calling clear()
vec.clear();
// recalculate size of vector
vecSize = vec.size();
cout << "After using clear(), size of vector: " << vecSize << endl;
cout << endl;
return 0;
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources