KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I was trying to erase a range of elements from map based on particular condition. How do I do it using STL algorithms? Initially I thought of using remove_if but it is not possible as remove_if does not work for associative container. Is there any "remove_if" equivalent algorithm which works for map ? As a simple option, I thought of looping through the map and erase. But is looping through the map and erasing a safe option?(as iterators get invalid after erase) I used following example: bool predicate(const std::pair<int,std::string>& x) { return x.first > 2; } int main(void) { std::map<int, std::string> aMap; aMap[2] = "two"; aMap[3] = "three"; aMap[4] = "four"; aMap[5] = "five"; aMap[6] = "six"; // does not work, an error // std::remove_if(aMap.begin(), aMap.end(), predicate); std::map<int, std::string>::iterator iter = aMap.begin(); std::map<int, std::string>::iterator endIter = aMap.end(); for(; iter != endIter; ++iter) { if(Some Condition) { // is it safe ? aMap.erase(iter++); } } return 0; }
Tags (comma-separated)
Save Edits
Cancel