Open In App

How to Delete All Elements from a Vector in C++?

Last Updated : 25 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, you can delete all items from a vector to either clear its contents or free its memory. In this article, we will learn how to delete all items from a vector in C++.

The recommended way to delete all items from a vector is by using the vector clear() function. Let’s take a look at a simple example:

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

int main() {
    vector<int> v = {1, 2, 3, 4, 5};

    // Clear the vector
    v.clear();

    cout << v.size();
    return 0;
}

Output
0

Explanation: The vector clear() function removes all elements from the vector, reducing its size to zero.

Note: Although clear() removes all elements, the vector's capacity (memory allocation) remains unchanged. To reduce memory usage, use shrink_to_fit() after clearing.

C++ provides a few more methods to delete all the elements and clear the vector. Some of them are as follows:

Using Vector erase()

The vector erase() function can remove all elements from a vector by specifying the range [begin, end).

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

int main() {
    vector<int> v = {1, 2, 3, 4, 5};

    // Erase all elements
    v.erase(v.begin(), v.end());

    cout << v.size();
    return 0;
}

Output
0

Explanation: Using the range as v.begin() and v.end() removes all elements.

By Swapping with Empty Vector

Swap the vector with an empty vector using vector swap() method to delete all elements and reset its capacity.

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

int main() {
    vector<int> v = {1, 2, 3, 4, 5};

    // Swap with an empty vector
    vector<int>().swap(v);

    cout << v.size();
    return 0;
}

Output
0

By Assigning Empty Vector

Instead of swapping, a vector can also be assigned an empty vector using vector assign() or simply = operator to delete all the elements. This method also clears the capacity.

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

int main() {
    vector<int> v = {1, 2, 3, 4, 5};

    // Assign an empty vector
    v = vector<int>();

    cout << v.size();
    return 0;
}

Output
0

Using Vector resize()

The vector resize()method can increase or decrease the size of vector, so to clear all elements of vector we can decrease its size to 0 using resize().

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

int main() {
    vector<int> v = {1, 3, 4, 6, 7};

    // Clear the vector
    v.resize(0);

    cout << v.size() << endl;
    return 0;
}

Output
0

Next Article
Article Tags :
Practice Tags :

Similar Reads