15

All the examples I can find for map::emplace use fairly simple types that have constructors that take a single argument, e.g.

std::map<std::string, std::string> foo;
foo.emplace("a", "b");

Suppose the value type constructor requires two parameters. Heck, let's really make it simple; suppose the value type is std::pair<std::string, double>. How do I use std::map<string, pair<string, double> >::emplace() to construct the value type in-place within the map?

I know this doesn't work:

std::map<std::string, std::pair<std::string, double> > foo;
foo.emplace("a", "b", 1.0);

At least, it fails loudly and at length on g++ 4.8.2. Is this even possible with C++11?

jzions
  • 431
  • 3
  • 9

1 Answers1

14

My search-fu was weak. This is actually answered, in great and illuminating detail, in another stackoverflow question.

The short answer:

foo.emplace(std::piecewise_construct,
            std::forward_as_tuple("a"),
            std::forward_as_tuple("b", 1.0));
Community
  • 1
  • 1
jzions
  • 431
  • 3
  • 9