A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/vector-erase-in-cpp-stl/ below:

Vector erase() in C++ STL

Vector erase() in C++ STL

Last Updated : 01 May, 2025

In C++, vector erase() is a built-in function that is used to delete elements from the vector. It removes an element of a specific position or range of elements from the vector.

Let’s take a simple example that uses the vector erase() method:

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

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

    // Remove the element at index 2
    v.erase(v.begin() + 2);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

In the above example, erase() method remove the element(3) which is present at index 2.

Syntax of Vector erase()

Vector erase method has two implementations:

C++
// Remove single element
v.erase(pos);

// Erase range of elements
v.erase(first, last);

where,

Parameters:

Return Value:

Examples of Vector erase()

The following programs illustrates how to use the vector erase() method to remove elements in different cases:

Remove an Element Using Index from a Vector C++
#include <bits/stdc++.h>
using namespace std;

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

    // Remove the element at index 1
    v.erase(v.begin() + 1);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Explanation: The iterator of the element at index 1 is determined by adding the index to vector begin() iterator. Then vector erase() is used to remove it.

Remove the Last Element from the Vector C++
#include <bits/stdc++.h>
using namespace std;

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

    // Remove the last element
    v.erase(v.end() - 1);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

In the above program, we use end() iterator to delete the last element of the vector, which is 5.

Remove a Range of Elements from a Vector C++
#include <bits/stdc++.h>
using namespace std;

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

    // Remove elements in the range [1, 4)
    v.erase(v.begin() + 1, v.begin() + 4);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Explanation: The iterator to the part of the vector to be removed is passed to the vector erase() method. It removed that part from the array.

Vector clear() and erase()

In a vector, both vector clear() and vector erase() are used for element removal, but they serve different purposes. Following are the cases which describe when to use clear() and when to use erase():



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4