+ 1

duplicate key in map also sort elements like map?

Hi i had assumption that when duplicate key is inserted in map, value gets updated into map. Same doesn't happen in below code. https://code.sololearn.com/cf85vGNiY96J Please share your views on this as I thought values get updated

21st May 2020, 4:23 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 ответов
+ 2
std::map::insert fails to insert a key if the key already exists. It does not update the value if it does exist. In this case it returns a pair where the first is the inserted iterator ( if successful ) and the second is a boolean that can tell you whether it succeeded. The behavior you describe only happens with the function std::map::operator[]. Note that since C++17 there is an insert_or_assign function.
21st May 2020, 4:32 PM
Dennis
Dennis - avatar
+ 2
If you want to have duplicate keys then use multimaps
29th May 2020, 3:29 PM
Anthony Maina
Anthony Maina - avatar