c++stllambdac++11erase-remove-idiom

Accessing for_each iterator from lambda


Is it possible to access the std::for_each iterator, so I can erase the current element from an std::list using a lambda (as below)

typedef std::shared_ptr<IEvent>    EventPtr;
std::list<EventPtr> EventQueue;
EventType evt;
...

std::for_each( 
    EventQueue.begin(), EventQueue.end(),

    [&]( EventPtr pEvent )
    {
        if( pEvent->EventType() == evt.EventType() )
            EventQueue.erase( ???Iterator??? );
    }
);

I've read about using [](typename T::value_type x){ delete x; } here on SO, but VS2010 doesn't seem to like this statement (underlines T as error source).


Solution

  • You are using the wrong algorithm. Use remove_if:

    EventQueue.remove_if([&](EventPtr const& pEvent)
    {
        return pEvent->EventType() == evt.EventType();
    });
    

    The STL algorithms do not give you access to the iterator being used for iteration. This is in most cases a good thing.

    (In addition, consider whether you really want to use std::list; it's unlikely that it is the right container for your use case. Consider std::vector, with which you would use the erase/remove idiom to remove elements that satisfy a particular predicate.)