vector::erase in C++ (With Examples)
Hello! Today, we’re going to discuss a widely-used function in C++ for managing elements in a vector - erase
. We’ll begin by exploring this function, learn the right way to use it, and see it in action with examples. By the end, you’ll have a solid grasp of this essential tool.
Removing Elements from a Vector in C++
Vectors in C++ are dynamic arrays that can grow and shrink in size. Sometimes, we need to remove elements from a vector, either a single element or a range of them. This is where the erase
function comes in handy.
The erase
function looks like this:
vector::erase(iterator position);
vector::erase(iterator first, iterator last);
- The function takes iterators for the first and the last elements to be removed.
- It returns an iterator pointing to the next element after the deleted one(s). If it removed the last element, then it would point to the vector’s end.
Example
Let’s see how it works with a simple program:
#include <iostream>
#include <vector>
int main() {
std::vector<int> my_vector;
// Add values from 1 to 10
for (int i=1; i<=10; i++) my_vector.push_back(i);
// Remove the 6th element
my_vector.erase(my_vector.begin()+5);
// Remove the first 3 elements
my_vector.erase(my_vector.begin(),my_vector.begin()+3);
std::cout << "my_vector contains:";
for (unsigned i=0; i<my_vector.size(); ++i)
std::cout << ' ' << my_vector[i];
std::cout << '\n';
return 0;
}
This program will give the output:
my_vector contains: 4 5 7 8 9 10
Important Points
When you remove an element (or several elements) from a vector:
- The size of the vector reduces by the number of elements you’ve removed.
- If you don’t remove elements from the end, the vector shifts all elements after the erased ones to new positions. This isn’t very fast compared to some other containers like
list
orforward_list
.
Complexity
The time it takes depends on two things: the number of elements you delete and the number of elements after the ones you delete. The latter are moved to new positions.
Iterators
Be careful with your iterators! If they point to a removed element or any element after it, they won’t work as you might expect. But iterators before the removed elements stay valid.
Safety and Exceptions
When you use erase
, it modifies the vector. But elements before the ones you remove aren’t touched. So, it’s safe to access or change them while using erase
. If you mistakenly give an invalid position or range to erase
, things can go unpredictably wrong, so be cautious.
Related functions
Just like the erase
function helps in managing elements in a vector, C++ offers many other utilities for different containers. For instance, if you wish to insert elements at a specific position in a vector, you can use the vector::insert
function. On the other hand, if you want to delete the last element from a vector, you can utilize the vector::pop_back
function. As you continue your journey in C++, exploring these functions will further deepen your understanding of the language’s capabilities.
Exercises
-
Basics of
erase
:
Write a C++ program that:- Creates a vector of strings, containing the names of five of your favorite movies.
- Asks the user for the name of a movie to remove from the vector.
- Uses the
erase
function to remove the movie if it exists in the vector. - Finally, displays the remaining movies in the vector.
-
Understanding Iterators and
erase
:
Modify the previous program to attempt to remove a movie based on its index (position) in the vector.- After removing a movie, try accessing an iterator that points to an element after the removed one. What happens? Include comments in your code explaining your observations.
- Also, display the movie at the position of the removed element after using
erase
. (Remember the function returns an iterator pointing to the next element after the deleted one.)
-
Comparing Performance with
list
orforward_list
:
Using your knowledge from the article and other resources:- Write a program that creates a large vector and a large list (e.g., containing 100,000 integers).
- Remove elements from the middle of both the vector and the list and measure the time it takes for each operation.
- Display the times and write a short analysis (1-2 paragraphs) on which container is faster for this kind of operation and why.
Discussion