Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Sorting Objects in a vector based on member boolean

In my program, I have classes I use for handling projectiles in a game.

class Projectile
{
bool IsActive;
bool GetActive();
//....
};

class Game
{
std::vector<Projectile*> ProjectilesToUpdate;
//....
};

Of course, there is more to it than that, however I'm trying to stay relevant to my current problem.

I want to use std::sort to make it so that all projectiles where IsActive == true are at the far beginning and that any projectile which isn't active is at the very end.

How would I go about doing this?

like image 406
Cupcake1029 Avatar asked Apr 23 '26 23:04

Cupcake1029


1 Answers

Basically, you want to create a partition:

std::partition(std::begin(ProjectilesToUpdate),
               std::end(ProjectilesToUpdate), 
               [](Projectile const* p) { return p->GetActive(); }
);

As for the subsidiary questions:

I had to remove the "const" part in the code to make it compile.

That's because your GetActive() method should be const:

bool GetActive() const { return IsActive; }

See Meaning of "const" last in a C++ method declaration?

how can I use this to delete every single object (and pointer to object) that is no longer needed?

You could use smart pointers (such as std::shared_ptr) and no longer care about delete. Thus you could use the Erase–remove idiom as follow:

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

Related question: What is a smart pointer and when should I use one?

If you don't want to use smart pointers, you could use the returned iterator which point to the first element of the second group (i.e. the non active ones) and iterate until the end of the array:

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

Note that I'm not calling erase inside the loop since it invalidates iterators.

And of course, this last solution is more complex than using smart pointers.

like image 114
Hiura Avatar answered Apr 26 '26 13:04

Hiura



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!