如何在迭代时从地图中删除?喜欢:
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) 我大致有以下代码.这可以更好或更有效吗?也许用std::remove_if?您可以在遍历地图时从地图中删除项目吗?我们可以避免使用临时地图吗?
typedef std::map<Action, What> Actions;
static Actions _actions;
bool expired(const Actions::value_type &action)
{
return <something>;
}
void bar(const Actions::value_type &action)
{
// do some stuff
}
void foo()
{
// loop the actions finding expired items
Actions actions;
BOOST_FOREACH(Actions::value_type &action, _actions)
{
if (expired(action))
bar(action);
else
actions[action.first]=action.second;
}
}
actions.swap(_actions);
}
Run Code Online (Sandbox Code Playgroud) 据称,当迭代器变为无效时,您不能在迭代时擦除/删除容器中的元素.删除满足特定条件的元素的(安全)方法是什么?请只是stl,没有提升或tr1.
编辑 如果我想删除符合某个标准的元素,可能使用仿函数和for_each或擦除算法,是否有更优雅的方法?