How do I efficiently remove_if only a single element from a forward_list?

后端 未结 5 1297
灰色年华
灰色年华 2021-01-18 03:00

Well I think the question pretty much sums it up. I have a forward_list of unique items, and want to remove a single item from it:

std::forward_list         


        
5条回答
  •  星月不相逢
    2021-01-18 03:25

    FWIW, here's another short version

    template< typename T, class Allocator, class Predicate >
    bool remove_first_if( std::forward_list< T, Allocator >& list, Predicate pred )
    {
        auto oit = list.before_begin(), it = std::next( oit );
        while( it != list.end() ) {
            if( pred( *it ) ) { list.erase_after( oit ); return true; }
            oit = it++;
        }
        return false;
    }
    

提交回复
热议问题