In this C++ tutorial, you will learn about vector::erase() function, its syntax, and how to use this function to remove an element at specific index in the vector, with example programs.
C++ Vector erase() function
erase() function removes an element at specific index, or removes a range of elements from specific start to end indices.
Syntax
The syntax of erase() function to remove an element at specific index is
iterator erase( const_iterator index );
The syntax of erase() function to remove all the elements from given start index until the end index is
iterator erase( const_iterator start, const_iterator end );
Please note that the position of element to be deleted has to be given as const_iterator
.
Examples
1. Remove element from vector at specific index
In the following C++ program, we initialise a vector names
with five elements, and then remove the element at index=3.
C++ Program
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> names{ "apple", "banana", "cherry", "mango" , "orange" };
names.erase( std::next(names.begin(), 2) );
for ( string x: names ) {
cout << x << endl;
}
}
Output
apple
banana
mango
orange
Program ended with exit code: 0
The element at index=2 has been removed from the vector.
2. Remove elements from vector in the index range [start, end)
In the following C++ program, we initialise a vector names
with five elements, and then remove the elements starting from index=2 up until index=4.
C++ Program
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> names{ "apple", "banana", "cherry", "mango" , "orange" };
int start = 2;
int end = 4;
names.erase( std::next(names.begin(), start),
std::next(names.begin(), end) );
for ( string x: names ) {
cout << x << endl;
}
}
Output
apple
banana
orange
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned the syntax of erase() function, and how to use this erase() function to remove an element from specific position or remove a range of elements present in the given index range.