How to delete an object from a map which contains a vector as value in C++ -
i have map contains of vector of type messages.
std::map<std::string, std::vector<message>> storage;
class message has 3 member variables.
class message { private: std::string msg; std::string msg_type; int priority; }
now trying delete object has priority(say 3) map. using following function it. doesn't work.
void deletebymessagepriority(int priority) { if (checkpriorityofmessage(priority)) { (std::map<std::string, std::vector<message>>::iterator = storage.begin(); != storage.end(); it++) { std::vector<message> listofmsgs = it->second; (std::vector<message>::iterator vec_it = listofmsgs.begin(); vec_it != listofmsgs.end(); vec_it++) //for(int index = 0;index < listofmsgs.size();index++) { if (vec_it->getpriority() == priority) { listofmsgs.pop_back(); } } } } }
look @ this:
if (vec_it->getpriority() == priority) { listofmsgs.pop_back(); }
you're looking @ priority of 1 message (the 1 referred vec_it
), deleting if matches?
instead of writing own loop, i'd use erase
, std::remove_if
remove items care in vector @ once.
for (auto & item : storage) { auto &vec = item.second; auto start_junk = std::remove_if( vec.begin(), vec.end(), [=](message const &m) { return m.priority == priority; }); vec.erase(start_junk, vec.end()); }
Comments
Post a Comment