Search code examples
c++listremove-if

list::remove_if equivalent


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;
            }
        }

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.