简体   繁体   English

迭代列表时C ++从列表中删除

[英]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. 我有一个std::list Bananas std::list ,我想摆脱坏的。 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.) (从C#和Java转换到C ++是一条艰难的道路。)

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. 请注意,你可能应该使用std::vector而不是std::list尽管 - 在99.9%的情况下, vector表现更好,并且它更容易使用。

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 : 编辑:如果你使用向量,向量没有remove_if成员函数,所以你必须使用命名空间std的普通remove_if

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. 编辑:由于remove_if被实现为std::list的成员函数,Billy ONeal的回答可能是更好的方式来完成所描述的工作,尽管如果你决定使用vector,deque时这会更容易转换等等,正如评论中已经讨论的那样,这可能是一件好事。

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). 或者,您可以使用list::remove_if方法或std::remove_if函数(也可以使用vector )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM