How to use emplace() in a std::map whose value is a std::set (map from something to a set)?

╄→гoц情女王★ 提交于 2019-12-06 11:17:24

Braced initializer lists have no type, so they can't be perfectly forwarded. In this particular case, you can specify the type (std::initializer_list<int>) explicitly if you want everything to be constructed in place:

misi.emplace(
  std::piecewise_construct,
  std::forward_as_tuple(2345),
  std::forward_as_tuple(std::initializer_list<int>{6, 9})
);

Since only one argument each is passed for the key and the value, and the initializer_list constructor of std::set is not explicit, you can remove the piecewise_construct altogether and have emplace construct the pair using the constructor taking two arguments:

misi.emplace(
  2345,
  std::initializer_list<int>{6, 9}
);

mii.emplace(std::pair<int, int>(2345, 6));

I wonder if the std::pair is constructed in-place or not. (Well, I guess not)

No, a temporary std::pair<int, int> is constructed and passed to emplace, which constructs an instance of the map's value_type (which is pair<const int, int>) with it. The latter is what is actually stored in the map.


misi.emplace(std::pair<int, std::set<int>>(2345, {6, 9}));

it seems that the std::set is created in-place (right?).

No. Again, this creates a temporary std::pair<int, std::set<int>>, and then constructs what's actually stored in the map (which is pair<const int, std::set<int>>) with it. This second construction will perform a move from the set<int> stored in the temporary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!