Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ removing from list while iterating over list

Tags:

c++

list

I have a std::list of Bananas, and I want to get rid of the bad ones. Is there any relatively simple way to perform the following pseudocode?

foreach(Banana banana in bananaList)
{
    if(banana.isBad()) bananaList.remove(banana);
}

(Making a transition from C# and Java to C++ has been a rocky road.)

like image 725
JnBrymn Avatar asked Feb 26 '23 15:02

JnBrymn


1 Answers

bananaList.remove_if(std::mem_fun_ref(&Banana::isBad));

Note that you should probably be using std::vector instead of std::list though -- vector performs better in 99.9% of cases, and it's easier to work with.

EDIT: If you were using vectors, vectors don't have a remove_if member function, so you'd have to use the plain remove_if in namespace std:

bananaVector.erase(
    std::remove_if(bananaVector.begin(), bananaVector.end(), std::mem_fun_ref(&Banana::isBad)), 
    bananaVector.end());
like image 158
Billy ONeal Avatar answered Mar 04 '23 13:03

Billy ONeal