How to Remove Elements from a List while Iterating in C++

Lists are sequence containers that allow for the allocation of non-contiguous memory. List traversal is slower than vector traversal, but once a position is found, insertion and deletion are fast. Normally, when we talk about a List, we mean a doubly linked list. We use a forward list to implement a singly linked list.

Given a list, the task is to remove the elements from the list while iterating through it.

Remove Elements from a List while Iterating in C++

The member function erase() of std::list accepts an iterator and deletes the element pointed by that Iterator. However, it renders that iterator invalid, i.e. we cannot use it because it has already been deleted and all of its links have become invalid.

As a result, std::list::erase() returns the iterator to the next element of the last deleted list. As a result, we can use this to continue iterating. Let’s look at how to delete all elements from a list that are divisible by 5 while iterating through the list.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Make a list and initialize it with some elements.
    list<int> arraylist(
        { 5, 5, 9, 10, 12, 15, 25, 65, 3, 4, 6, 7, 25 });
    // Iterate through the list using Iterators, removing
    // elements
    // that are divisible by 5 as you go.
    list<int>::iterator itr = arraylist.begin();
    // loop till end of list
    while (itr != arraylist.end()) {
        // Removing the elements which are divisible by 5
        // while iterating through it
        if ((*itr) % 5 == 0) {
            // The passed iterator is rendered invalid by
            // erase().
            // However, the iterator is returned to the next
            // deleted element.
            itr = arraylist.erase(itr);
        }
        else { // increment the iterator
            itr++;
        }
    }
    // print the list after reemoving the elements
    for (auto itr = arraylist.begin();
         itr != arraylist.end(); ++itr)
        cout << *itr << " ";
    return 0;
}

 

Output:

9 12 3 4 6 7

Leave a Comment