Search code examples
c++dictionaryiteratorerase

Erase key, value from map by value in C++


My map is defined like this:

map<string, map<string, string>> _map;

But the problem that has come up is that my map's first is mostly the same value, i.e.

_map["key1"]["value1"] = "data1";
_map["key1"]["value2"] = "data2";
_map["key1"]["value3"] = "data3";
_map["key1"]["value4"] = "data4";
_map["key2"]["value5"] = "data5";

So when I want to delete any particular (key, value), I can't use _map.find("key1") for the iterator because it has duplicate entries.

Is there a way to set the iterator index using the value?

Suppose I want to delete this entry:

_map["key1"]["value4"] = "data4";

How would I do this?


Solution

  • Nawaz's answer is correct. It does have one weakness, however: If you erase "value5", _map["key2"] will still contain an empty map<string, string>. This is probably not what you intend.

    To fix this, you can use the pair template and change the type of _map to be:

    map<pair<string, string>, string> _map;
    

    Your assignments would then look like:

    _map[make_pair("key1", "value1")] = "data1";
    _map[make_pair("key1", "value2")] = "data2";
    _map[make_pair("key1", "value3")] = "data3";
    _map[make_pair("key1", "value4")] = "data4";
    _map[make_pair("key2", "value5")] = "data5";
    

    Then you can remove each entry like:

    _map.erase(make_pair("key1", "value4"));
    

    You can find the pair type in the <utility> header.