c++ - 如何在不复制条目值的情况下在 std::map 中创建新条目 - 无指针

标签 c++ c++11 std stdmap

我有一张 map :

std::map<std::string, MyDataContainer>

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);

有办法吗?当我只想在 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/

相关文章:

c++ - 模板化类时模板不能是虚拟错误

c++ - 如何定义双括号/双迭代器运算符,类似于 Vector of Vectors'?

c++ - 如何使用 qmake 设置 C++ 项目的可执行属性?

c++ - C++中无序集的大小是否有限制

c++ - 我可以使用 std::copy 将数据的位模式从整数 vector 复制到 unsigned char 数组吗

c++ - 使用 decltype 和\或 std::remove_reference 调用析构函数

c++ - 与非 C++ 代码的链接

c++ - 错误: aggregate has incomplete type and cannot be defined

c++ - 如何简洁、便携和彻底地播种 mt19937 PRNG?

c++ 序列化 std::error_code 以通过网络传输或保存到磁盘?