Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For a map of objects, can I emplace objects, or just pairs?

I'm using C++ 11 and gcc-4.7.0. I'm looking for an STL solution.

I'd like to have an unsorted multimap that contains objects of myClass with short strings as keys. Emplace looks like a good way to put the objects into the map as I construct them, but I'm not sure if it can do that, or if it will only construct the key/object pair. This should be valid:

table.emplace(myKey, myClass(arg1, arg2, arg3));

But would it be more efficient to do the following, and is it even valid code?

table.emplace(myKey, arg1, arg2, arg3);
like image 224
Qaz Avatar asked Mar 23 '14 02:03

Qaz


1 Answers

According to this, gcc-4.7 does not fully support emplace().

gcc-4.8 would have fully support of emplace(), but would require a little differnt syntax:

table.emplace(std::piecewise_construct, std::forward_as_tuple(myKey), std::forward_as_tuple(arg1, arg2, arg3));

instead of

table.emplace(myKey, arg1, arg2, arg3); // Does not work.

For forward to take effect for rvalue, one could use std::move() to wrap around the arguments.

So it will directly contruct both key and value in place in the container.

std::piecewise_construct is an argument for special usage of std::pair constructor. It will ask the constructor to forward the arguments individually to underlying constructor.

This is actually an issue of emplace() for associative containers. The original intention is to use the first argument for key, and the following arguments for value, like what is described in the question. See this for further details on this issue.

Thanks to Zeta, for pointing out forward issue.

like image 127
WiSaGaN Avatar answered Oct 08 '22 17:10

WiSaGaN