ERASE()
This function is used to remove elements from containers such as std::vector
, std::list
, std::deque
, std::map
, std::set
, and others in the Standard Template Library (STL). Its behavior and parameters vary slightly depending on the container type. For sequence containers like vector
and list
, erase()
can remove a single element using an iterator or a range of elements using two iterators. For associative containers like map
and set
, it can remove elements by key, by iterator, or by a range of iterators. When called, erase()
adjusts the container to maintain valid structure, and in the case of vectors or deques, this might involve shifting elements. Importantly, for containers like vector
, erasing elements invalidates iterators and references to the erased and subsequent elements.
vectorName.erase(positionIterator); // Removes a single element
vectorName.erase(startIterator, endIterator); // Removes a range of elements
* positionIterator: Iterator to the element to be removed (e.g., vec.begin() + index)
* startIterator, endIterator: The range of elements to remove (endIterator is exclusive)
REMOVING A SINGLE ITEM
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Step 1: Initialize a vector of numbers
vector<int> numbers = {10, 20, 30, 40, 50};
// Step 2: Remove the third element (index 2, value 30)
numbers.erase(numbers.begin() + 2);
// Step 3: Print updated vector using a normal for loop
cout << "Updated numbers:" << endl;
for (int i = 0; i < 4; i++) { // After erasing, vector has 4 elements
cout << numbers[i] << " ";
}
return 0;
}
OUTPUT:
Updated numbers:
10 20 40 50
REMOVING A RANGE OF ITEMS
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Step 1: Initialize a vector of months
vector<string> months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"};
// Step 2: Remove elements from index 2 (Mar) to index 5 (excluding Jul)
months.erase(months.begin() + 2, months.begin() + 6);
// Step 3: Print updated vector using normal for loop
cout << "Remaining months:" << endl;
for (int i = 0; i < 3; i++) { // Remaining: Jan, Feb, Jul
cout << months[i] << " ";
}
return 0;
}
OUTPUT:
Remaining months:
Jan Feb Jul
Last updated