Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map<K,V>::emplace where V constructor requires two parameters

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?

like image 921
jzions Avatar asked Apr 30 '15 22:04

jzions


1 Answers

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));
like image 102
jzions Avatar answered Oct 07 '22 00:10

jzions