How do I avoid iterator invalidation with std::list?

In C++, when working with `std::list`, iterators can sometimes become invalidated due to operations such as insertions or deletions. However, because `std::list` is a doubly linked list, insertions and deletions do not invalidate iterators pointing to other elements in the list. They only invalidate the iterators that point to the specific element that is being removed. To avoid iterator invalidation, one can maintain the iterators to elements that are still valid while performing operations on the list.

#include #include int main() { std::list myList = {1, 2, 3, 4, 5}; auto it = myList.begin(); // Get iterator to the first element while (it != myList.end()) { if (*it % 2 == 0) { it = myList.erase(it); // erase returns the next valid iterator } else { ++it; // move to the next element } } // Output remaining elements for (const auto& value : myList) { std::cout << value << " "; // should output 1 3 5 } return 0; }

iterator invalidation std::list C++ programming list manipulation safe iterator usage