Last Updated : 23 Jul, 2025
In this article, we will learn how to remove a given element from the vector in C++.
The most straightforward method to delete a particular element from a vector is to use the vector erase() method. Let's look at a simple example that shows how to use this function:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 5, 7, 4};
// Removing 7 from vector v
v.erase(find(v.begin(), v.end(), 7));
for (auto i : v)
cout << i << " ";
return 0;
}
Explanation: The vector erase() function removes the element using iterator not value, so iterator to the element to be removed is determined using find() function.
C++ also provide more methods to delete the element or multiple elements from the given vector. Some of them are as follows:
Using remove() with Vector pop_back()The remove() function shift an element that have to be remove to the end of vector. The last element is then deleted by vector pop_back() method.
Example C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 5, 7, 4};
// Shifting 7 to the end of vector
remove(v.begin(), v.end(), 7);
// Deleting the last element i.e. 7
v.pop_back();
for (auto i : v)
cout << i << " ";
return 0;
}
We can also use vector erase() method to delete the last element.
Using vector clear()The vector clear() method is used when all the elements of the vector have to be removed.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 5, 7, 4};
// Removing all the elements
v.clear();
for (auto i : v)
cout << i << " ";
return 0;
}
Output
(empty)
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