删除for(-each)自动循环中的项目 [英] Erasing item in a for(-each) auto loop
问题描述
在这样的for循环中使用自动变量时有没有办法擦除特定元素?
Is there a way to erase specific elements when using a auto variable in a for loop like this?
for(auto a: m_Connections)
{
if(something)
{
//Erase this element
}
}
我知道我可以说
for(auto it=m_map.begin() ...
或
for(map<int,int>::iterator it=m_map.begin() ...
并手动递增迭代器(和擦除),但如果我能用更少的代码行完成,我会更高兴。
and manually increment the iterator (and erase) but if I could do it with less lines of code I'd be happier.
谢谢!
推荐答案
不,没有。范围基于loop用于访问容器的每个元素一次。
No, there isn't. Range based for loop is used to access each element of a container once.
每次从容器中删除元素时,擦除元素处或之后的迭代器不再有效(和给出基于范围的实现 - 这是一个问题)。
Every time an element is removed from the container, iterators at or after the erased element are no longer valid (and given the implementation of the range-based-for this is a problem).
你应该使用正常for循环(或而
),如果你需要随时修改容器。
You should use the normal for loop (or a while
) if you need to modify the container as you go along.
如果你想要删除谓词返回 true
的元素,一个好方法是:
If you want to erase elements for which a predicate returns true
, a good way is:
m_Connections.erase(
std::remove_if(m_Connections.begin(),
m_Connections.end(),
[](Type elem) { return predicate(elem); }),
m_Connections.end());
std :: remove_if 不会将迭代逻辑与谓词混合。
std::remove_if doesn't mix iteration logic with the predicate.
这篇关于删除for(-each)自动循环中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!