Open In App

Vector clear() in C++ STL

Last Updated : 09 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, vector clear() is a built-in method used to remove all elements from a vector, making it empty. In this article, we will learn about the vector clear() method in C++.

Let’s take a look at an example that illustrates the vector clear() method:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {11, 23, 45, 9};

    // Remove all elements from the vector
    v.clear();

    // Check if the vector is empty
    if (v.empty()) {
        cout << "Vector is Empty";
    }
    else {
        cout << "Vector is Not Empty";
    }
    return 0;
}

Output
Vector is Empty

This article covers the syntax, usage, and common examples of the vector clear() method in C++ STL.

Syntax of Vector clear()

The vector clear() method is defined inside the std::vector class in the <vector> header file.

v.clear();

This function does not take any parameters, nor it returns any value.

Examples of Vector clear()

The below examples demonstrate the use and behaviour of vector clear() method in practical scenarios.

Delete All the Elements of a Vector

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {11, 23, 45, 9};

    // Clear the vector
    v.clear();

    // Check the size of the vector
    cout << v.size();

    return 0;
}

Output
0

Effect of Vector clear() on the Capacity

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {11, 23, 45, 9};
  
  	// Initial capacity
  	cout << v.capacity() << endl;

    // Clear the vector
  	v.clear();
  
  	cout << v.capacity();
    return 0;
}

Output
4
4

Explanation: As we can see, the vector clear() method does not affects the capacity of the vector. It means that although it deletes the memory


Next Article
Practice Tags :

Similar Reads