如何在迭代时从地图中删除? [英] How to remove from a map while iterating it?
问题描述
如何在迭代时从地图中移除?例如:
How do I remove from a map while iterating it? like:
std::map<K, V> map;
for(auto i : map)
if(needs_removing(i))
// remove it from the map
如果我使用 map.erase
,它将使迭代器无效
If I use map.erase
it will invalidate the iterators
推荐答案
标准关联容器删除成语:
The standard associative-container erase idiom:
for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
if (must_delete)
{
m.erase(it++); // or "it = m.erase(it)" since C++11
}
else
{
++it;
}
}
注意,我们真的想要一个普通的 for
循环,因为我们正在修改容器本身。基于范围的循环应该严格保留用于我们只关心元素的情况。 RBFL的语法通过甚至不暴露循环体中的容器使这一点清楚。
Note that we really want an ordinary for
loop here, since we are modifying the container itself. The range-based loop should be strictly reserved for situations where we only care about the elements. The syntax for the RBFL makes this clear by not even exposing the container inside the loop body.
编辑。Pre-C ++ 11,你不能删除const迭代器。您必须说:
Edit. Pre-C++11, you could not erase const-iterators. There you would have to say:
for (std::map<K,V>::iterator it = m.begin(); it != m.end(); ) { /* ... */ }
从容器中删除元素不会与元素的constness不一致。类似地, delete p
始终是完全合法的,其中 p
是指针常数。恒定不限制生命; C ++中的const值仍然可以停止存在。
Erasing an element from a container is not at odds with constness of the element. By analogy, it has always been perfectly legitimate to delete p
where p
is a pointer-to-constant. Constness does not constrain lifetime; const values in C++ can still stop existing.
这篇关于如何在迭代时从地图中删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!