如何在不复制条目值的情况下在 std::map 中创建新条目 - 无指针
How to create new entry in std::map without copying the entry value - no pointers
我有一张地图:
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
:请参阅 documentation
m.emplace(std::piecewise_construct,
std::forward_as_tuple(42), // argument of key constructor
std::forward_as_tuple()); // argument of value constructor
使用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 */);
我有一张地图:
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
:请参阅 documentation
m.emplace(std::piecewise_construct,
std::forward_as_tuple(42), // argument of key constructor
std::forward_as_tuple()); // argument of value constructor
使用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 */);