In this tutorial, we will learn about erase() member function of vector in C++.

In C++ STL, the std::vector class is a Sequential Container, which provides the flexibility of Dynamic Array that can be resized on the fly. The vector class the erase() member function, which is used to remove elements from the vector. This function can remove a single element or a range of elements from a vector. It’s particularly useful for situations where you need to modify the contents of a vector by removing specific elements based on their position.

Syntax of vector::erase()

The erase() function in C++ vector has two commonly used overloads:

iterator erase(iterator position);
iterator erase(iterator first, iterator last);

These functions remove elements from the vector at specified positions.

Parameters of vector::erase()

The parameters for the erase() function are as follows:

  • position: An iterator pointing to the single element to be removed (for the first overload).
  • first, last: Iterators specifying the beginning and end of a range of elements to be removed (for the second overload). The range includes the element pointed to by first but does not include the element pointed to by last.

Return Value of vector::erase()

The erase() function returns an iterator pointing to the position immediately following the last removed element. If no elements are removed, the return value is the same as the position or first parameter.

Examples of vector::erase()

Example 1: Erasing a Single Element

First we will create & initialize a vector named numbers with some default values i.e.

std::vector<int> numbers = {11, 22, 33, 44, 55};

Next, we will use the erase() function to remove the third element (in this case, 33) by specifying an iterator that points to the desired element for deletion. Like this,

// Erasing the third element
numbers.erase(numbers.begin() + 2);

The begin() function returns an iterator pointing to the first element of the vector. Then, we incremented it by 2 to make it point to the third element of the vector. Afterward, we passed this iterator to the erase() function, which removes the element pointed to by that iterator. Now the contents of vector will be,

11, 22, 44, 55

Let’s see the complete example,

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> numbers = {11, 22, 33, 44, 55};

    // Erasing the third element
    numbers.erase(numbers.begin() + 2);

    std::cout << "Vector after erasing the third element: ";
    for (int element : numbers) {
        std::cout << element << " ";
    }

    return 0;
}

Output

Vector after erasing the third element: 11 22 44 55

In this code, the third element (number 33) is removed from vector numbers.

Example 2: Erasing a Range of Elements

Suppose we have a vector named numbers, initialized with some default values i.e.

std::vector<int> numbers = {11, 22, 33, 44, 55};

Now, if we want to remove three elements from this vector, specifically the second, third, and fourth elements, we can achieve this by passing two iterators defining a range within the vector into the erase() function. The start of the range will be numbers.begin() + 1, which is an iterator pointing to the second element in the vector. The end of the range will be numbers.begin() + 4, which is an iterator pointing to the fifth element of the vector.

We will pass these two iterators to the erase() function, and it will remove the elements from index position 1 (the second element) up to index position 3 (one less than the end of the range provided in the erase() function). This way, it will remove the elements in the specified range, leaving the rest of the vector intact.

// Erasing elements from the second to the fourth
numbers.erase(numbers.begin() + 1, numbers.begin() + 4);

It will remove 3 elements of vector i.e. from the second to the fourth position in vector. Contents of vector will be like,

11 55 66

Let’s see the complete example,

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> numbers = {11, 22, 33, 44, 55, 66};

    // Erasing elements from the second to the fourth
    numbers.erase(numbers.begin() + 1, numbers.begin() + 4);

    std::cout << "Vector after erasing a range of elements: ";
    for (int element : numbers)
    {
        std::cout << element << " ";
    }

    return 0;
}

Output

Vector after erasing a range of elements: 11 55 66

Here, the second, third, and fourth elements are removed from vector numbers.

C++ Vector erase() and Iterator Invalidation

The erase() function in C++ can cause iterator invalidation, because when it removes an element from the vector, it may shift the positions of remaining elements in the vector to fill the gap left by the removed element. This shifting of elements can invalidate iterators that were pointing to elements within the vector.

Here’s an example that demonstrates how erase() can cause iterator invalidation:

Let’s see the complete example,

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> numbers = {11, 22, 33, 44, 55};

    // Attempt to erase the first element
    // (element at index 0) using an iterator
    std::vector<int>::iterator it = numbers.begin();
    numbers.erase(it);

    // Now Iterator "it" is Invalid

    // This line would now lead to undefined behavior, as 'it' is invalidated.
    std::cout << "The first element after erasure: " << *it << std::endl;

    return 0;
}

Output

The first element after erasure: 22

In this example, we have a vector of integers and attempt to erase the first element (element at index 0) using an iterator it. However, after the call to numbers.erase(it), the iterator it becomes invalidated because the elements in the vector are shifted, and it is no longer pointing to a valid element within the container. Attempting to dereference the invalidated iterator, as shown in the cout statement, leads to undefined behavior.

To avoid iterator invalidation, you should be cautious when using the erase() function and update iterators accordingly. For example, as vector::erase() function returns an iterator pointing to the position immediately following the last removed element, so you can use the iterator returned by erase() to get the next valid iterator and continue iterating through the container safely. Here’s an example of how to use the erase() function with the iterator returned by it to delete elements from a std::vector in a loop:

Let’s see the complete example,

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> numbers = {11, 22, 33, 44, 55};

    // Let's say we want to remove all even numbers from the vector.
    // We'll use the erase() function in a loop.

    // Create an iterator pointing to the beginning of the vector.
    std::vector<int>::iterator it = numbers.begin();

    // Iterate through the vector using a while loop.
    while (it != numbers.end()) {
        // Check if the current element is even.
        if (*it % 2 == 0) {
            // Erase the current element and update the iterator to the next element.
            it = numbers.erase(it);
        } else {
            // If the current element is not even, just move to the next element.
            ++it;
        }
    }

    // Print the updated vector.
    std::cout << "Vector after removing even numbers: ";
    for (int element : numbers) {
        std::cout << element << " ";
    }

    return 0;
}

Output

Vector after removing even numbers: 11 33 55

In this example:

  1. We start with a std::vector named numbers containing some default values.
  2. We want to remove all even numbers from the vector.
  3. We create an iterator it that points to the beginning of the vector using numbers.begin().
  4. We use a while loop to iterate through the vector.
  5. Inside the loop, we check if the current element pointed to by it is even. If it’s even, we erase the element using it = numbers.erase(it), which not only removes the element but also updates the iterator to point to the next element in the vector. If it’s not even, we simply increment the iterator ++it to move to the next element.
  6. The loop continues until we reach the end of the vector.
  7. Finally, we print the updated vector to show that all even numbers have been successfully removed.

It removed all even numbers from the numbers vector and print the updated vector, which will only contain the odd numbers.

Summary

Today, we learned how the vector::erase() function remove either a single element or a range of elements from a std::vector.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.