Home >Backend Development >C++ >How to Safely Delete Elements from a std::list During Iteration?

How to Safely Delete Elements from a std::list During Iteration?

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 04:25:11485browse

How to Safely Delete Elements from a std::list During Iteration?

Deleting Elements During Iteration in a std::list

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.

Avoiding Multiple Passes

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn