C++ removing from list while iterating over 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# a开发者_运维百科nd Java to C++ has been a rocky road.)
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());
You'd typically do something like:
list.erase(std::remove_if(list.begin(), list.end(), std::mem_fun(Banana::isBad)), list.end());
Edit: Thanks to remove_if
being implemented as a member function of std::list
, Billy ONeal's answer is probably the better way to do the job as described, though this would be easier to convert when/if you decide to use a vector, deque, etc., which, as already discussed in comments, is probably a good thing to do.
You can use a homebrew code like
for(list<...>::iterator it=bananas.begin(); end=bananas.end(); it!=end;) {
if(... decide ...) {
it=bananas.erase(it);
} else
++it;
}
or, you can use the list::remove_if
method, or std::remove_if
function (which is usable with a vector
, too).
精彩评论