如何从 std::map 中过滤项目?

2021-12-24 00:00:00 c++ stl boost

我大致有以下代码.这可以做得更好或更有效吗?也许使用 std::remove_if ?您可以在遍历地图时从地图中删除项目吗?我们可以避免使用临时地图吗?

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

推荐答案

你可以使用 erase(),但我不知道 BOOST_FOREACH 将如何处理失效的迭代器.map::erase 的文档 指出只有被擦除的迭代器才会被删除失效了,其他的应该没问题.下面是我将如何重构内部循环:

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

相关文章