Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emplace empty vector into std::map()

Tags:

c++

stl

How can I emplace an empty vector into a std::map? For example, if I have a std::map<int, std::vector<int>>, and I want map[4] to contain an empty std::vector<int>, what can I call?

like image 926
quantumwell Avatar asked Oct 15 '25 03:10

quantumwell


2 Answers

Unfortunately the strictly-correct answer is indeed to use std::piecewise_construct as the first argument, followed by two tuples. The first represents the arguments to create the key (4), and the second represents the arguments to create the vector (empty argument set).

It would look like this:

map.emplace(std::piecewise_construct,   // signal piecewise construction
            std::make_tuple(4),         // key constructed from int(4)
            std::make_tuple());         // value is default constructed

Of course this looks unsightly, and other alternatives will work. They may even generate no more code in an optimised build:

This one notionally invokes default-construction and move-assignment, but it is likely that the optimiser will see through it.

map.emplace(4, std::vector<int>());

This one invokes default-construction followed by copy-assignment. But again, the optimiser may well see through it.

map[4] = {};
like image 176
Richard Hodges Avatar answered Oct 19 '25 13:10

Richard Hodges


If you use operator[](const Key&), the map will automatically emplace a value-initialized (i.e. in the case of std::vector, default-constructed) value if you access an element that does not exist. See here:

http://en.cppreference.com/w/cpp/container/map/operator_at

(Since C++ 11 the details are a tad more complicated, but in your case this is what matters).

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.

Demo: https://godbolt.org/g/rnfW7g

like image 34
Max Langhof Avatar answered Oct 19 '25 13:10

Max Langhof