When iterating through a std::list, removing elements while maintaining a valid iterator can be challenging. Consider the following code:
for (std::list<item*>::iterator i = items.begin(); i != items.end(); i++) { bool isActive = (*i)->update(); //if (!isActive) // items.remove(*i); //else other_code_involving(*i); } items.remove_if(CheckItemNotActive);
Adding the commented-out lines to remove inactive items immediately would result in a "List iterator not incrementable" error. This is because removing an element invalidates the iterator.
To remove items efficiently while iterating, consider a while loop approach:
std::list<item*>::iterator i = items.begin(); while (i != items.end()) { bool isActive = (*i)->update(); if (!isActive) { items.erase(i++); // alternatively, i = items.erase(i); } else { other_code_involving(*i); ++i; } }
The key here is to increment the iterator before removing the element. Alternatively, "i = items.erase(i)" can be used. This allows for safe and efficient removal of elements while iterating.
The above is the detailed content of How to Safely Delete Elements from a std::list During Iteration?. For more information, please follow other related articles on the PHP Chinese website!