Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 910
fishfood Avatar asked Jun 28 '12 14:06

fishfood


2 Answers

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.)

like image 59
James McNellis Avatar answered Oct 15 '22 02:10

James McNellis


no, use a regular for instead.

for( auto it = EventQueue.begin(); it != EventQueue.end(); ++it )
{
  auto pEvent = *it;
  if( pEvent->EventType() == evt.EventType() )
      it = EventQueue.erase( it );
);
like image 30
smerlin Avatar answered Oct 15 '22 02:10

smerlin