If some key is already present in the map then what will happen
If some key is already present in the map and we are trying the insert different value with same key then what will happen
If some key is already present in the map then what will happen
If some key is already present in the map and we are trying the insert different value with same key then what will happen
If you use insert
, emplace
, emplace_hint
or try_emplace
, nothing is changed in the map.
If you assign through []
or use insert_or_assign
, the value you supply replaces the existing value.
In a c++ std::map the previous existing value is overwritten. This is the desired standard behavior of a map.
The same is true for similar map-constructs in any programming language, e.g. "dict" in python etc.
The value that is already in the map will simply get overwritten if you simply assign using []
or insert_or_assign
I've put below an example of what you can expect
int main()
{
map<string, int> mp = { {"Hello", 1} };
std::cout << mp["Hello"];
//outputs 1
mp["Hello"] = 15;
std::cout << mp["Hello"];
//outputs 15
}
but if you are using insert
, emplace
, emplace_hint
or try_emplace
and the value is already inside the map, then nothing will happen to the map.