How do I erase elements while writing std::list?

Asked 1 years ago, Updated 1 years ago, 70 views

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);

I want to remove the inactive item from !isActive right away If you clear the comment, the Listator not incremental error occurs when you do i++. I tried not to do i++ but the same error occurred.

How can I erase the elements while eterating the list?

list c=+ std

2022-09-22 22:24

1 Answers

After removing i, it is because i++. Since there is no i now, it is impossible to calculate, so an error occurs.

Like j=i, you must save i somewhere, then i++ and erase the element with j. Please change the code as follows

std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
    bool isActive = (*i)->update();
    if (!isActive)
    {
        items.erase(i++); // or i = items.erase(i);
    }
    else
    {
        other_code_involving(*i);
        ++i;
    }
}


2022-09-22 22:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.