Emplacement of a vector with initializer list

m47h picture m47h · Jul 3, 2014 · Viewed 9.8k times · Source

i have a std::vector<std::vector<double>> and would like to add some elements at the end of it so this was my trial:

std::vector<std::vector<double> > vec;
vec.emplace_back({0,0});

but this does not compile whereas the following will do:

std::vector<double> vector({0,0});

Why can't emplace_back construct the element at this position? Or what am i doing wrong?

Thanks for your help.

Answer

Tim Kuipers picture Tim Kuipers · Nov 16, 2016

The previous answer mentioned you could get the code to compile when you construct the vector in line and emplace that. That means, however, that you are calling the move-constructor on a temporary vector, which means you are not constructing the vector in-place, while that's the whole reason of using emplace_back rather than push_back.

Instead you should cast the initializer list to an initializer_list, like so:

#include <vector>
#include <initializer_list>

int main()
{
    std::vector<std::vector<int>> vec;
    vec.emplace_back((std::initializer_list<int>){1,2});
}