Question

I'd like to know if its possible to represent this expression using remove_if and a lambda expression.

        std::list< gh::Actor* >::iterator astit = actors.begin();
        while (astit != actors.end())
        {           
            if( (*astit)->state == DELETE_STATE )
            {           
                Actor* reference = *astit;
                actors.erase(astit++);

                delete reference;
            }
            else
            {
                ++astit;
            }
        }
Was it helpful?

Solution

actors.erase(
  std::remove_if( actors.begin(), actors.end(), []( gh::Actor*a )->bool {
    if (!a || a->state == DELETE_STATE) {
      delete a;
      return true;
    } else {
      return false;
    }
  }),
  actors.end()
);

As an aside, you almost certainly do not want to use std::list. Use std::vector -- the cases where std::list outperforms std::vector are exceedingly narrow.

OTHER TIPS

Better use smart pointers with lambda.

Try:

std::list<std::shared_ptr<gh::Actor>> actors;
actors.remove_if([](std::shared_ptr<Actor>& a){ return a->state == DELETE_STATE; });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top