Erasing items from an STL list

前端 未结 6 1942
北恋
北恋 2021-02-02 13:21

I want to make a function which moves items from one STL list to another if they match a certain condition.

This code is not the way to do it. The iterator will most lik

6条回答
  •  感动是毒
    2021-02-02 13:44

    template 
    void splice_if(ForwardIterator begin, ForwardIterator end, OutputIterator out, Predicate pred)
    {
        ForwardIterator it = begin;
        while( it != end )
        {
            if( pred(*it) )
            {
                *begin++ = *out++ = *it;
            }
            ++it;
        }
        return begin;
    }
    
    myList.erase( 
        splice_if( myList.begin(), myList.end(), back_inserter(myOutputList),
            myCondition
        ),
        myList.end()
    )
    

提交回复
热议问题