如何在std :: map中创建新条目而不复制条目值 - 没有指针

Tom*_*ica 1 c++ stdmap std c++11

我有一张地图:

std::map<std::string, MyDataContainer>
Run Code Online (Sandbox Code Playgroud)

MyDataContainer一些classstruct(无所谓).现在我想创建一个新的数据容器.假设我想使用默认构造函数来实现它:

// 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);
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?当我想在地图中初始化它时跳过创建辅助变量?是否有可能使用构造函数参数?

我认为这个问题也适用于其他std容器,比如.

Ker*_* SB 7

用途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());
Run Code Online (Sandbox Code Playgroud)

这概括为新键值和映射值的任意consructor参数,您只需将其放入相应的forward_as_tuple调用中.

在C++ 17中,这有点容易:

m.try_emplace("nocopy"  /* mapped-value args here */);
Run Code Online (Sandbox Code Playgroud)