Given this type:
std::map<int, std::vector<T>> map;
How to directly emplace elements?
map.emplace(10, /* ? */);
I can do it by separately creating the vector first, and then using that identifier in the call to emplace, but that is undesirable in case it's possible to do it directly somehow.
This post will discuss how to convert a vector of pairs to a map in C++. 1. Using std::copy A simple option to copy all elements from a vector to a map is using the std::copy standard algorithm from header <algorithm>. Its usage is demonstrated below: 2. Using copy constructor
That means if your map is empty and you do map [4], it will readily give you a reference to an empty (default-constructed) vector. Assigning an empty vector is unnecessary, although it may make your intent more clear. Unfortunately the strictly-correct answer is indeed to use std::piecewise_construct as the first argument, followed by two tuples.
Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. Map of Vectors in STL: Map of Vectors can be very efficient in designing complex data structures.
2. Using emplace: emplace is also used to insert the pairs into the map. This function is similar to “insert ()” discussed above, the only difference being that “in-place” construction of pair takes place at the position of element insertion contrary to insert () which copies or movies existing object.
Both
map.emplace(typename decltype(map)::value_type(10, {1, 2, 3}));
and
map.emplace(10, std::initializer_list<int>{1, 2, 3});
should work fine.
I'm sure there is a reason why gcc rejects my first attempt:
map.emplace(10, {1, 2, 3});
but I don't know if it is a good reason or a defect.
Edit: It seems to have to do with the fact that the braced initializer list ({1, 2, 3}
) does not have a type, making it impossible to use with perfect forwarding (which is necessary for map.emplace
). There are several relevant SO posts about this point, such as this answer.
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