简体   繁体   中英

How to remove objects and pointers from vector of pointers by object parameter

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.

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());
//...

如果我有auto* event_queue_ = new vector<Event>而不是vector <Event*> event_queue_怎么vector <Event*> event_queue_

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM