如何筛选从一个std ::地图项目? [英] How to filter items from a std::map?

查看:133
本文介绍了如何筛选从一个std ::地图项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我大致有以​​下code。难道这是取得更好或更有效?也许使用的std ::的remove_if ?您可以从地图上同时穿越它删除项目?我们可以避免使用临时地图吗?

 的typedef的std ::地图<作用,什么>操作;
静态操作_actions;布尔过期(常量操作:: VALUE_TYPE&安培;动作)
{
  返回<东西取代;
}无效杆(常量操作:: VALUE_TYPE&安培;动作)
{
  //做一些东西
}无效美孚()
{
  //循环行动发现过期的项目
  操作行动;
  BOOST_FOREACH(操作:: VALUE_TYPE&安培;作用,_actions)
  {
    如果(过期(动作))
      杆(动作);
    其他
      行动[action.first] = action.second;
    }
  }
  actions.swap(_actions);
}


解决方案

您可以使用擦除(),但我不知道BOOST_FOREACH将如何处理失效的迭代器。在地图的文档::擦除只擦除迭代器就会失效状态,其他人应该没问题。下面是我会怎么调整内部循环:

 操作:迭代它= _actions.begin();
而(它!= _actions.end())
{
  如果(过期(*吧))
  {
    酒吧(*它);
    操作:迭代toerase =它;
    ++它;
    _actions.erase(toerase);
  }
  其他
    ++它;
}

I have roughly the following code. Could this be made nicer or more efficient? Perhaps using std::remove_if? Can you remove items from the map while traversing it? Can we avoid using the temporary map?

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);
}

解决方案

You could use erase(), but I don't know how BOOST_FOREACH will handle the invalidated iterator. The documentation for map::erase states that only the erased iterator will be invalidated, the others should be OK. Here's how I would restructure the inner loop:

Actions::iterator it = _actions.begin();
while (it != _actions.end())
{
  if (expired(*it))
  {
    bar(*it);
    Actions::iterator toerase = it;
    ++it;
    _actions.erase(toerase);
  }
  else
    ++it;
}

这篇关于如何筛选从一个std ::地图项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆