To comply with C++11 you’re unfortunately a bit limited in how you can tackle this. Your options basically boil down to:
-
Iterate over the
unordered_mapand build a list of keys to delete like so://std::unordered_map<...> mymap; std::vector<decltype(mymap)::key_type> vec; for (auto&& i : mymap) if (/*compare i*/) vec.emplace_back(i.first); for (auto&& key : vec) mymap.erase(key); -
Iterate over the object and reset if we find something to remove – I’d really only recommend this for small datasets. those of you who feel goto is unconditionally bad, well, this option is arguably bad.
//std::unordered_map<...> mymap; reset: for (auto&& i : mymap) if (/*compare i*/) { mymap.erase(i.first); goto reset; } -
As a somewhat out there option, you could also just create a new
unordered_mapand move the elements that you want to keep. This is arguably a good option when you have more to delete than to keep.//std::unordered_map<...> mymap; decltype(mymap) newmap; for (auto&& i : mymap) if (/*i is an element we want*/) newmap.emplace(std::move(i)); mymap.swap(newmap);