Tom*_*ica 1 c++ stdmap std c++11
我有一张地图:
std::map<std::string, MyDataContainer>
Run Code Online (Sandbox Code Playgroud)
在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);
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?当我想在地图中初始化它时跳过创建辅助变量?是否有可能使用构造函数参数?
用途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)
| 归档时间: |
|
| 查看次数: |
1249 次 |
| 最近记录: |