C++ remove element from vector while iterating – How to Remove Elements from a List while Iterating in C++?

C++ remove element from vector while iterating: Do you feel it difficult to remove elements in a list while iterating in C++? Then, this tutorial is going to be quite helpful as its lists all about what is meant by a list, how to remove elements in a list while iterating in C++. Check out Program to Remove Elements from a List while iterating in CPP explained in detail in the further modules and simply copy-paste the code if you are asked any kind of question in your exams.

Lists – Definition

List remove 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++

Java remove element from list while iterating: 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:

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

#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

Related Programs: