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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With