如何将无参数构造函数的对象放置到std :: map中? [英] How to emplace object with no-argument constructor into std::map?
问题描述
我想将一个对象放置到 std :: map
中,该对象的构造函数不接受任何参数。但是, std :: map :: emplace
除了键之外,似乎还需要至少一个附加参数。那么如何将零参数转发给构造函数?
I want to emplace an object into a std::map
whose constructor does not take any arguments. However, std::map::emplace
seems to require at least one additional argument besides the key. So how can I forward zero arguments to the constructor?
推荐答案
std :: map<的元素类型; K,V>
实际上是 std :: pair< K,V>
,因此当您嵌入到地图中时,参数将是转发给 std :: pair
的构造函数。这就是为什么您不能仅传递键的原因: std :: pair< K,V>
不能由单个参数构造(除非它是另一对相同的参数)类型。)您可以传递零个参数,但是键将被值初始化,这可能不是您想要的。
The element type of std::map<K, V>
is actually std::pair<K, V>
, so when you are emplacing into a map, the arguments will be forwarded to the constructor of std::pair
. That's why you can't pass just the key: std::pair<K, V>
can't be constructed from a single argument (unless it's another pair of the same type.) You can pass zero arguments, but then the key will be value-initialized, which is probably not what you want.
在大多数情况下,移动值将是价格便宜(并且密钥很小且可复制),您实际上应该只执行以下操作:
In most cases, moving values will be cheap (and keys will be small and copyable) and you should really just do something like this:
M.emplace(k, V{});
其中 V
是映射类型。它将被值初始化并移入容器。 (此举甚至可能会被忽略;我不确定。)
where V
is the mapped type. It will be value-initialized and moved into the container. (The move might even be elided; I'm not sure.)
如果您无法移动,并且确实需要 V
要就地构造,必须使用分段构造构造器...
If you can't move, and you really need the V
to be constructed in-place, you have to use the piecewise construction constructor...
M.emplace(std::piecewise_construct, std::make_tuple(k), std::make_tuple());
这会导致 std :: pair
的构造第一个元素使用 k
,第二个元素使用零参数(值初始化)。
This causes std::pair
to construct the first element using k
and the second element using zero arguments (value-initialization).
这篇关于如何将无参数构造函数的对象放置到std :: map中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!