如何在迭代时从地图中删除?喜欢:
std::map<K, V> map;
for(auto i : map)
if(needs_removing(i))
// remove it from the map
Run Code Online (Sandbox Code Playgroud)
如果我使用map.erase它将使迭代器无效
我试图根据特定情况从地图中删除一系列元素.我如何使用STL算法?
最初我想使用remove_if但不可能因为remove_if不适用于关联容器.
是否有适用于地图的"remove_if"等效算法?
作为一个简单的选项,我想到循环遍历地图并擦除.但是循环遍历地图并删除安全选项?(因为迭代器在擦除后变为无效)
我使用以下示例:
bool predicate(const std::pair<int,std::string>& x)
{
return x.first > 2;
}
int main(void)
{
std::map<int, std::string> aMap;
aMap[2] = "two";
aMap[3] = "three";
aMap[4] = "four";
aMap[5] = "five";
aMap[6] = "six";
// does not work, an error
// std::remove_if(aMap.begin(), aMap.end(), predicate);
std::map<int, std::string>::iterator iter = aMap.begin();
std::map<int, std::string>::iterator endIter = aMap.end();
for(; iter != endIter; ++iter)
{
if(Some Condition)
{
// is it safe ?
aMap.erase(iter++);
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)