Why does std::map
not support an insert like the following:
std::map<obj1, obj2> map_int;
void insert_map(obj1 &key, obj2 &val)
{
map_int.insert(key, val);
}
I know that the above is incorrect. I want to know what prevents from designing the insert function like that. It is more intuitive than creating a pair IMO.
It's called emplace()
:
std::map<std::string, std::string> m; // uses pair's template constructor m.emplace("d", "ddd");
In C++17, you can use:
map_int.try_emplace(key, val);
This actually returns some useful information:
std::pair<std::map<obj1, obj2>::iterator, bool> p = map_int.try_emplace(key, val);
p.first
is an iterator that points to the element with the given key.p.second
indicates whether the insertion took place.You can achieve a similar effect in C++11 with map_int.emplace(key, val)
, but there are some subtle differences (related to copying/moving of values). Moreover, try_emplace
allows for convenient construction of arbitrary elements:
struct X { X(int, char, bool); };
std::map<int, X> m;
m.try_emplace(10, 20, 'x', false); // constructs X(20, 'x', false) if new
A similar operation in C++11 would look like this:
m.emplace(
std::piecewise_construct,
std::forward_as_tuple(10),
std::forward_as_tuple(20, 'x', false));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With