Mark Ransom算法的一种变体,但不需要临时的.
for(Actions::iterator it = _actions.begin();it != _actions.end();) { if (expired(*it)) { bar(*it); _actions.erase(it++); // Note the post increment here. // This increments 'it' and returns a copy of // the original 'it' to be used by erase() } else { ++it; // Use Pre-Increment here as it is more effecient // Because no copy of it is required. } }
你可以使用erase(),但我不知道BOOST_FOREACH将如何处理无效的迭代器.map :: erase的文档说明只有擦除的迭代器才会失效,其他的应该没问题.这是我如何重构内循环:
Actions::iterator it = _actions.begin(); while (it != _actions.end()) { if (expired(*it)) { bar(*it); Actions::iterator toerase = it; ++it; _actions.erase(toerase); } else ++it; }