Reputation: 53119
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 stdvector or stdlist.
Upvotes: 1
Views: 1503
Reputation: 476960
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 */);
Upvotes: 7
Reputation: 217085
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
Upvotes: 2