Reputation: 3435
std::map<std::string, Obj> myMap;
std::set<std::string> mySet;
I want to remove those pairs from myMap
which keys are not in mySet
.
How do I do it? I found std::remove_if
algorithm, but it seems to not be applicable here.
Upvotes: 1
Views: 532
Reputation: 477040
I'd start with this simple approach:
for (auto it = myMap.begin(); it != myMap.end(); )
{
if (mySet.find(it->first) == mySet.end()) { myMap.erase(it++); }
else { ++it; }
}
If you want something more efficient, you could iterate both containers in lockstep and do key-wise comparisons to take advantage of the compatible element order. On the other hand, the present algorithm works even on unordered containers, and given that your keys are strings, unordered containers may have a better performance anyway.
Upvotes: 6