1

我想知道是否可以使用 remove_if 和 lambda 表达式来表示这个表达式。

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

2 回答 2

2

更好地smart pointerslambda.

尝试:

std::list<std::shared_ptr<gh::Actor>> actors;
actors.remove_if([](std::shared_ptr<Actor>& a){ return a->state == DELETE_STATE; });
于 2013-01-25T00:47:12.483 回答
2
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()
);

顺便说一句,您几乎可以肯定不想使用std::list. 使用std::vector——std::list表现优异的情况std::vector非常狭窄。

于 2013-01-25T00:58:37.923 回答