Here is my code:
map <pair<int,int> ,string> m;
m.insert(make_pair(1,2),"imtiaz");//making key value pair
m.insert(make_pair(8,3),"moin");
m.insert(make_pair(1,2),"izm");
cout<<m[make_pari(1,2)]<<endl; //print value for key 1,2
output:
imtiaz
We know if we insert a value for existing key in map, it will update the value.Here for same key (1,2) I insert two values "imtiaz" and "izm".So,latest value "izm" should print here.What is the wrong here?
It is the intended behavior of insert
to not overwrite existing entries in the map.
Use insert_or_assign
(C++17) for the behavior you expect. In older C++ versions, use assignment with operator[]
to update (or insert) an element.
So why was insert_or_assign
introduced? From the link above:
insert_or_assign returns more information than operator[] and does not require default-constructibility of the mapped type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With