Removing Element using two iterators
Using 2 iterators is just the same just rather than operating over the iterator we operate over the dummy iterator so that when the iterator is incremented it comes to its right position.
Example:
C++
// C++ Program to implement Removing of // element while iterating using // 2 iterators #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 = li.begin(); // Before Deletion cout << "Before Deletion: " << endl; cout << "Size of List: " << li.size() << endl; print(li); // Deleting element from list while iterating // through iterator while (it != li.end()) { list< int >::iterator temp = it++; if (*temp % 3 == 0) { temp = li.erase(temp); } } // 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; } |
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