基本上,你想创建一个partition:
std::partition(std::begin(ProjectilesToUpdate),
std::end(ProjectilesToUpdate),
[](Projectile const* p) { return p->GetActive(); }
);
关于附属问题:
我必须删除代码中的“const”部分才能使其编译。
那是因为你的 GetActive() 方法应该是 const:
bool GetActive() const { return IsActive; }
见Meaning of "const" last in a C++ method declaration?
如何使用它来删除不再需要的每个对象(和指向对象的指针)?
您可以使用智能指针(例如std::shared_ptr)而不再关心删除。因此您可以使用Erase–remove idiom 如下:
std::vector<std::shared_ptr<Projectile>> ProjectilesToUpdate;
// :
// :
auto it = std::remove_if(
std::begin(ProjectilesToUpdate),
std::end(ProjectilesToUpdate),
[](std::shared_ptr<Projectile> const& p) { return !p->GetActive(); } // mind the negation
);
ProjectilesToUpdate.erase(it, std::end(ProjectilesToUpdate));
相关问题:What is a smart pointer and when should I use one?
如果你不想使用智能指针,你可以使用返回的迭代器,它指向第二组的第一个元素(即非活动元素)并迭代直到数组的末尾:
auto begin = std::begin(ProjectilesToUpdate);
auto end = std::end(ProjectilesToUpdate);
auto start = std::partition(begin, end,
[](Projectile const* p) { return p->GetActive(); }
);
for (auto it = start; it != end; ++it) {
delete *it;
}
ProjectilesToUpdate.erase(start, end);
请注意,我没有在循环内调用 erase,因为它会使迭代器无效。
当然,最后一个解决方案比使用智能指针更复杂。