Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why c++ map value don't update for same key?

Tags:

c++

stl

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?

like image 532
Imtiaz Mehedi Avatar asked Dec 03 '22 17:12

Imtiaz Mehedi


1 Answers

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.

like image 84
ypnos Avatar answered Dec 18 '22 19:12

ypnos