Vector erase() in C++ STL (original) (raw)

Last Updated : 25 May, 2026

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.

C++ `

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

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

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

// Print the modified vector
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

Vector erase method has two implementations:

// 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:

**Example: Remove an Element Using Index from a Vector

C++ `

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

int main() { vector 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.

**Example: Remove the Last Element from the Vector

C++ `

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

int main() { vector 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.

**Example: Remove a Range of Elements from a Vector

C++ `

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

int main() { vector 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():

Time Complexity: