-1
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?

neckutrek
  • 353
  • 2
  • 14
  • The [documentation for `std::multimap::emplace`](http://en.cppreference.com/w/cpp/container/multimap/emplace) seems pretty clear on its course of action. The opening sentence, "Inserts a new element into the container constructed in-place with the given args" leaves little to the imagination, and differs from that of [`std::map::emplace`](http://en.cppreference.com/w/cpp/container/map/emplace) in the lack of any prior-element qualifier. – WhozCraig Dec 28 '16 at 11:00
  • Moreover, question - what will `cout` produce?, when you can easily check it yourself, is quite strange... – zoska Dec 28 '16 at 11:01

3 Answers3

0

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

neckutrek
  • 353
  • 2
  • 14
0

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

paweldac
  • 1,144
  • 6
  • 11
0

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.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • I think the question results from misunderstanding what `emplace` means in this case. I think OP doesn't realize that `emplace` is really `insert` but with C++11 semantics. – zoska Dec 28 '16 at 11:03