Reputation: 3
I have a vector of pointers to Event object like this:
std::vector <Event*> event_queue_;
This is my Event class
class Event{
...
bool IsAlarmSensitiveEvent();
bool alarm_sensitive_event_;
...
};
I would like to remove pointers from vector of pointers and Event objects when alarm_sensitive_event_ is true.
I tried to do this like this:
for (Event* x : event_queue_)
{
if (x != nullptr)
{
for (int i = 0; i < event_queue_.size(); i++)
{
if (event_queue_.at(i)->IsAlarmSensitiveEvent())
{
std::cout << "Removing event " << event_queue_.at(i)->NameOfEvent() << std::endl;
delete event_queue_.at(i);
event_queue_.erase(event_queue_.begin() + i);
removed = true;
}
}
}
}
It is working but I think loop in the loop isn't the best way so I'm looking for something better.
Upvotes: 0
Views: 71
Reputation: 35440
Using this answer as a guide, you can partition off the elements to delete first, delete them, then erase them from the vector:
#include <vector>
#include <algorithm>
//…
// Partition the elements to delete (place the items to delete on right side of vector)
auto iter = std::stable_partition(event_queue.begin(), event_queue.end(),
[](Event *x) { return !x->IsAlarmSensitiveEvent(); });
// Deallocate them
std::for_each(iter, event_queue.end(), [](Event *x)
{
std::cout << "Removing event " << x->NameOfEvent() << "\n";
delete x;
});
// Erase them from vector
event_queue.erase(iter, event_queue.end());
//...
Upvotes: 1
Reputation: 35
What if I have auto* event_queue_ = new vector<Event>
instead of vector <Event*> event_queue_
?
Upvotes: 0