Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emplacing vector into map

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.

like image 733
Anonymous Entity Avatar asked Feb 27 '15 17:02

Anonymous Entity


People also ask

How to convert a vector to a map in C++?

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

How to assign an empty vector to a map?

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.

Why vector vector elements are placed in contiguous storage?

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.

What is the difference between insert () and emplace () in MAP2?

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.


1 Answers

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.

like image 178
rici Avatar answered Sep 25 '22 09:09

rici