c++ - How to insert key and value to map that is inside another map in cpp? -
i have map :
std::map<std::string, std::map<std::string, std::string> > objects;
as far know, when write objects[key]
replace value of key exists, here want add second map if pair doesn't exist.
example: current map :("key1",map(<"key_a","value_a">,<"key_c","value_d">)) input: "key1", "key_e","value_f" relsult: ("key1",map(<"key_a","value_a">,<"key_c","value_d">,<"key_e","value_f">)) input : "key1", "key_e","value_g" (replace value "value_f" "value_g") result: ("key1",map(<"key_a","value_a">,<"key_c","value_d">,<"key_e","value_g">)) , if "key2" -> insert new key empty map
can :
objects[key].insert(std::make_pair(key2,value2))
it didn't work reason
can please advise?
as far know, when write
objects[key]
replace value of key exists, here want add second map if pair doesn't exist.
that's wrong: if write objects[key]
doesn't replace anything, ever; rather:
if
objects
doesn't containkey
, inserts new pair in map key , value uses default constructed (in case empty)std::map<std::string, std::string>
. returns reference value.if
objects
containkey
, returns reference existing value (the "inner" map) without changing or replacing anything.
can this:
objects[key].insert(std::make_pair(key2,value2))
you could, if [key][key2]
existing wouldn't update value value2
, assume want , why "it didn't work".
all have is:
objects[key][key2] = value2;
because objects[key]
never replaces existing map
, default-constructs 1 if key
's missing, key2
either finds existing entry in "inner" map needs updating or creates it, hangs (if i've understood requirement correctly).
Comments
Post a Comment