Does std::multimap::emplace overwrite old keys?

1.7k views Asked by At
std::multimap<int,std::string> mymap;
mymap.emplace(1, "hello ");
mymap.emplace(1, "world!");
std::cout << mymap.size() << "\n";

Will this echo 1 or 2? I.e., can I use emplace to add new pairs to a multimap, without affecting older pairs with the same key?

3

There are 3 answers

0
paweldac On

Best to check on your own. From definition std::multimap allowes to have same key for different values, std::map doesn't. Output is: 2, so it's allowed to have 2 different values under same key in multimap.

IdeONE: https://ideone.com/eRkBmV

1
SingerOfTheFall On

From [associative.reqmts]/4 (emphasis mine):

An associative container supports unique keys if it may contain at most one element for each key. Otherwise, it supports equivalent keys. The set and map classes support unique keys; the multiset and multimap classes support equivalent keys. For multiset and multimap, insert, emplace, and erase preserve the relative ordering of equivalent elements

In fact the whole point of multimap is to be able to store multiple elements with the same key, as opposed to map.

0
neckutrek On

By trial on http://cpp.sh/ this outputs 2, emplace does not overwrite old pairs with the same key.