Home >Backend Development >C++ >How to Remove Elements from a C Standard Map Based on a Condition?
Equivalent of Remove-If for Standard Maps
Question:
In C , how can I remove a range of elements from a map based on a specified condition using the STL algorithm?
Answer:
While remove_if algorithm is not applicable for associative containers like maps, there exists an equivalent approach using iterators. Here's how you can do it:
bool predicate(const std::pair<int, std::string>& x) { return x.first > 2; } int main() { std::map<int, std::string> aMap; // Populate the map... std::map<int, std::string>::iterator iter = aMap.begin(); std::map<int, std::string>::iterator endIter = aMap.end(); for (; iter != endIter;) { if (predicate(*iter)) { // Here, increment iter after erasing iter = aMap.erase(iter); } else { ++iter; } } }
Explanation:
The above is the detailed content of How to Remove Elements from a C Standard Map Based on a Condition?. For more information, please follow other related articles on the PHP Chinese website!