简体   繁体   中英

How to create new entry in std::map without copying the entry value - no pointers

I have a map:

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

The MyDataContainer is some class or struct (doesn't matter). Now I want to create a new data container. Let's say I wanna do it with default constructor available:

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

Is there way to do that? To skip creating helper variable when I just wanna initialize it in map? And would it be possible to do it with constructor arguments?

I think this question also applies to other std containers, like or .

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

This generalizes to arbitrary consructor arguments for the new key value and mapped value, which you just stick into the respective forward_as_tuple calls.

In C++17 this is a bit easier:

m.try_emplace("nocopy"  /* mapped-value args here */);

You may use map::emplace : see documentation

m.emplace(std::piecewise_construct,
          std::forward_as_tuple(42), // argument of key constructor
          std::forward_as_tuple());  // argument of value constructor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM