我有一张 map :
std::map<std::string, MyDataContainer>
MyDataContainer
是一些class
或struct
(无关紧要)。现在我想创建一个新的数据容器。假设我想使用可用的默认构造函数来做到这一点:
// This is valid, MyDataContainer doesn't need constructor arguments
MyDataConstructor example;
// The map definition
std::map<std::string, MyDataContainer> map;
std::string name("entry");
// This copies value of `example`
map[name] = example;
// Below, I want to create entry without copy:
std::string name2 = "nocopy"
// This is pseudo-syntax
map.createEmptyEntry(name2);
有办法吗?当我只想在 map 中初始化它时跳过创建辅助变量?是否可以使用构造函数参数来实现?
最佳答案
使用emplace
:
#include <map>
#include <string>
#include <tuple>
std::map<std::string, X> m;
m.emplace(std::piecewise_construct,
std::forward_as_tuple("nocopy"),
std::forward_as_tuple());
这概括为新键值和映射值的任意构造函数参数,您只需将其粘贴到相应的 forward_as_tuple
调用中即可。
在 C++17 中,这更容易一些:
m.try_emplace("nocopy" /* mapped-value args here */);
关于c++ - 如何在不复制条目值的情况下在 std::map 中创建新条目 - 无指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34022088/