Q:

How to neatly move some elements from std::set to another container?

Since iterator invalidates upon remove operation, how do I iterate with the least amount of code over all the elements of std::set, removing some of them ?

A:

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

