简体   繁体   中英

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, ie

_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?

Just erase it:

 _map["key1"].erase("value4");

Note that it doesn't throw exception if the key doesn't exist — it returns 0 in that case.

BTW, you can improve the initialization of the map as:

std::map<std::string, std::map<std::string, std::string>> _map 
{
   {"key1", {
               {"value1", "data1"},
               {"value2", "data2"},
               {"value3", "data3"},
               {"value4", "data4"}
             }
    },
    {"key2", {
                {"value5", "data5"}
             }
     }
 };

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM