Erasing elements from unordered_map in a loop

To comply with C++11 you’re unfortunately a bit limited in how you can tackle this. Your options basically boil down to:

  1. Iterate over the unordered_map and 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);
    
  2. 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;
        }
    
  3. As a somewhat out there option, you could also just create a new unordered_map and 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);
    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)