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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?