在 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.
谢谢!
推荐答案
不,没有.基于范围的 for 循环用于访问容器的每个元素一次.
No, there isn't. Range based for loop is used to access each element of a container once.
每次从容器中删除元素时,删除元素处或之后的迭代器不再有效(并且给定 range-based-for的实现这是一个问题.
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 循环(或 while
).
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屋!