In this article, we will discuss how to remove elements from vector while iterating and avoid the iterator invalidation issue.

In C++, the vector class provides a member function erase(), to remove a single or multiple elements from vector. We are going to use that to delete elements from vector while iterating / in for loop. But before that, let’s have an overview of vector::erase() function.

Overview of vector::erase() function

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

Arguments:

  • To delete single element from a vector using erase() function, pass the iterator of element to it like erase(it). It will delete the element pointed by the iterator the it variable.
  • To delete multiple elements from a vector using erase() function, pass the iterator range to it like erase(start, end-1). It will delete the elements from start to end-1, where start & end are the iterators.

Returns:

  • It returns an iterator pointing to the new location of the next entity in vector i.e. the element followed the last deleted element.

C++ : Delete elements from vector in loop

While iterating over a vector in a loop, if any of its element gets deleted then all the existing iterator becomes invalidated. It means, if in a loop we call the erase() function to delete elements, then after that we need to reset the iterator to correct position and then only continue the loop.

For this we can use the value returned by the erase() function i.e. iterator pointing to the new location of the next entity in vector i.e. the element followed the last deleted element. Set the iterator returned by erase() to the existing iterator variable and continue the loop.

Let’s checkout the existing example to delete elements from a vector while iterator in a for loop.

In this example, we will iterator over a vector of numbers and during iteration, for each element we will check if it is an even number or not. If yes, then we will delete that element, then set the iterator to next element and continue the loop. For example,

#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector<int> vecObj {11, 22, 33, 44, 55, 66, 77, 44, 34};

    // Print the vector contents
    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;

    // Iterate over a vector using range based for-loop
    // and remove all the even numbers from vector in loop
    auto it = vecObj.begin();
    while(it != vecObj.end()) {
        // If element is even number then delete it
        if(*it % 2 == 0) {
            // Due to deletion in loop, iterator became
            // invalidated. So reset the iterator to next item.
            it = vecObj.erase(it);
        } else {
            it++;
        }
    }

    // Print the vector contents
    for(auto elem : vecObj) {
        cout<<elem<<", ";
    }
    cout<<endl;
}

Output:

11, 22, 33, 44, 55, 66, 77, 44, 34, 
11, 33, 55, 77, 

We deleted all the even numbers for a vector of integers in a for loop.

Summary:

Today, we learned how to delete an element from a vector while iterating.

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.