由于迭代器在删除操作时无效,如何使用最少量的代码迭代所有元素std::set,删除其中的一些元素?
// Filters the elements of a set: elements that satisfy the predicate 'pred'
// are removed from the source set and inserted into the output.
template <typename TSet, typename TOutputIterator, typename TPredicate>
void extract_if(TSet& s, TOutputIterator out, TPredicate pred)
{
for (typename TSet::iterator it(s.begin()); it != s.end();)
{
if (pred(*it))
{
*out++ = *it;
it = s.erase(it);
}
else
{
++it;
}
}
}
Run Code Online (Sandbox Code Playgroud)