Iterating in for loop
There is no such change in the while and for loop, just the way to increment is changed which can be quite confusing.
Below is the implementation of the above topic
C++
// C++ Program for removing elements // in a list using single iterator // in for loop #include <iostream> #include <list> using namespace std; // Function to print elements From // the list While iterating void print(list< int >& li) { auto it = li.begin(); if (it == li.end()) { cout << "List is Empty" << endl; } for (it; it != li.end(); it++) { cout << *it << " " ; } cout << endl; } // Function to delete elements From // the list While iterating void solve(list< int >& li) { list< int >::iterator it; // Before Deletion cout << "Before Deletion: " << endl; cout << "Size of List: " << li.size() << endl; print(li); // Deleting element from list while iterating // through it-- for ( auto it = li.begin(); it != li.end(); it++) { if (*it % 3 == 0) { it = li.erase(it); it--; } } // After Deletion cout << "\nAfter Deletion: " << endl; cout << "Size of List: " << li.size() << endl; print(li); } // Driver Code int main() { list< int > li = { 1, 2, 3, 5, 4, 6 }; solve(li); return 0; } |
Output
Before Deletion: Size of List: 6 1 2 3 5 4 6 After Deletion: Size of List: 4 1 2 5 4
C++ Remove Elements From a List While Iterating
Prerequisite: List in C++
Removing elements is a necessary task for any container. Removing elements from a list is an easy task as we have predefined pop_back and pop_front functions but as the list is a container following the properties of a doubly linked list there should be a method to remove elements while iterating.
You cannot directly delete the element from the list while iterating because of doing you get Runtime Error because the iterator is now pointing to NULL and the address of the next element of the list gets lost and you cannot access the list anymore.
Contact Us