b.g*_*.g. 0 c++ unordered-map emplace c++14
我的 unordered_map 分别带有 string 和 aClass 类型的键值对;aClass 不能移动的地方(它有一个互斥锁)。我也不希望它是复制构造的;我认为复制构造一个包含互斥锁的类是不明智的。为了将项目的构建延迟到其插入到地图中,我尝试使用 emplace 将其插入到地图中,因此,第二个参数必须为空:
aList.emplace("aString");
Run Code Online (Sandbox Code Playgroud)
但是,前一行不起作用。任何想法如何使用默认构造函数放置?我也试过:
aList.emplace("aString", void);
aList.emplace("aString", {});
aList.emplace(std::piecewise_construct,"aString");
Run Code Online (Sandbox Code Playgroud)
谢谢,
如果您有权访问 C++17,则可以使用try_emplace:
myMap.try_emplace("someKey");
Run Code Online (Sandbox Code Playgroud)
这将默认构造一个带有键“someKey”的新元素。
在 C++17 之前,您可以使用emplaceusingstd::pair的std::piecewise_construct构造函数和一个空元组作为值的参数:
myMap.emplace(std::piecewise_construct,
std::forward_as_tuple("someKey"),
std::tuple<>{});
Run Code Online (Sandbox Code Playgroud)