vector::erase() function in C++

In this article, we will discuss all about vector’s erase() function, and how to use the vector::erase() function in C++.

Table Of Contents

In C++, the vector class provides a function erase() to delete single or multiple elements from vector.

It has 2 overloaded implementation. Let’s look at his syntax,

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

Now we will discuss these 2 implementations one by one

Advertisements

Remove single element from vector using erase()

For this we will use this overloaded implementation of erase function

iterator erase (const_iterator position);

Parameters

  • position : An iterator pointing to the element to be deleted.

Returns

  • An iterator pointing to the element followed by the deleted element.

It accepts a single argument that is the iterator pointing to the element that needs to be deleted, and removes that element from the vector. It also returns the iterator pointing to the element followed by the last deleted element.

Let us see an example,

Suppose we have a vector of five integers and now we want to delete the 3rd element from the vector. For that, first we need to create an iterator pointing to the 3rd element of the vector. Then we need to pass that iterator to the erase() function. It will delete the element from the vector. Let’s see the example

#include <iostream>
#include <vector>

int main ()
{
    // create a vector, and initialize with five integers
    std::vector<int> vectorObj {11, 12, 13, 14, 15};

    // Get iterator pointing to the third element of vector
    auto it = vectorObj.begin() + 2;

    // Remove third element of vector
    vectorObj.erase(it);

    // Print all elements of vector
    for (const int& num: vectorObj) {
        std::cout<< num <<", ";
    }
    std::cout<<std::endl;

    return 0;
}

Output

11, 12, 14, 15, 

The begin() function of vector gives us the iterator pointing to the first element of the vector. Then we added 2 in the iterator, to make it point to the 3rd element of the vector. Then we passed this iterator to the erase() function, and it deleted the element pointed by this iterator i.e. the 3rd element of the vector.

Removing multiple elements from vector using erase() function

For this we will use the second implementation of vector function. In which, it accepts two arguments that is iterators representing a range. Let us see the syntax of the

iterator erase (const_iterator first, const_iterator last);

Parameters

  • first: Iterator pointing to the start of a range in the vector
  • last: Iterator pointing to the end of a range in the vector

Returns

  • It returns an iterator pointing to the element followed by the last deleted element in vector.

Let us see an example,

Suppose we have a vector of 10 integers. We want to delete first five elements from the vector. For that we need to pass following arguments in the erase() function,

  • Iterator pointing to the first element of the vector
  • Iterator pointing to the sixth element of the vector into the erase() function.

It will delete all elements from first till 5th element of vector. Let’s see the complete example

#include <iostream>
#include <vector>

int main ()
{
    // create a vector, and initialize with five integers
    std::vector<int> vectorObj {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};

    // Remove first five elements of vector
    vectorObj.erase(vectorObj.begin(), vectorObj.begin() + 5);

    // Print all elements of vector
    for (const int& num: vectorObj) {
        std::cout<< num <<", ";
    }
    std::cout<<std::endl;

    return 0;
}

Output:

16, 17, 18, 19, 20, 

We passed 2 iterators in the erase() function. The first iterator was pointing to the beginning of vector, and the second iterator was pointing to the 6th element of the vector. The erase() functioned deleted the elements from first iterator till the second iterator. It will not delete the element pointed by second iterator i.e. it will delete till one element before the element pointed by the second itertor.

Using vector::erase() function in the for loop

Before going ahead, let’s discuss an important point. When we call the erase() function, it removes an element from the vector. If you are removing an element from the starting of the vector or anywhere from the vector, then it will invalidate all the iterators of that vector.

So if you are using a for loop with an iterator, to iterate over all the elements of vector and you want to delete certain elements during iteration, based on condition, using the erase() function. Then it will invalidate all the existing iterators. So your for loop can behave in an unexpected manner. To resolve this kind of issue, we need to reassign the invalid iterator to the next correct value. How we will do that? Let’s see the example

#include <iostream>
#include <vector>

int main ()
{
    // create a vector, and initialize with five integers
    std::vector<int> vectorObj {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; 

    // Iterate over all elements of vector
    for(auto it = vectorObj.begin(); it != vectorObj.end(); it++)
    {
        // Check if number is even or not
        if ((*it) % 2 == 0)
        {
            // delete number from vector if even
            it = vectorObj.erase(it);
        }
        // break from for-loop
        if(it == vectorObj.end())
        {
            break;
        }
    }


    // Print all elements of vector
    for (const int& num: vectorObj) {
        std::cout<< num <<", ";
    }
    std::cout<<std::endl;

    return 0;
}

Output:

11, 13, 15, 17, 19, 

Here we are using a for loop to iterate over all elements of a vector and we are using iterators. During iteration, we deleted the elements which are even and then we reassigned the value returned by erase() function to the iterator it. It is because, just after the erase() function returns, our existing iterators are invalidated. So we need to correct them.

The erase() function returns an iterator pointing to the element followed by the last deleted element. So we assigned it back to the variable it. This way our invalid iterator will become valid again, so we can continue in the for loop

So this is how we can use vector’s erase() function in the for loop.

Summary

We learned all the ways to use vector::erase() function in C++, to remove elements from the vector. Thanks for reading.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top