Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emplacement of a vector with initializer list

Tags:

c++

emplace

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.

like image 222
m47h Avatar asked Jul 03 '14 10:07

m47h


People also ask

How to initialize a vector in C++?

A very popular and common way to Initialize a Vector nowadays is through the use of a C++ Initializer List. Initializers Lists are actually used to initialize all manner of containers and variables, and are used in Arrays and Classes.

How to initialize multi-dimensional vectors using initializer lists?

Initializer lists are not limited to just normal Vectors, and can be used to initialize multi-dimensional vectors as well. All you have to do is nest initializer lists within each other as shown below. The number of nested curly-bracket pairs decides how many vectors are inserted into the 2D Vector.

How to cast a brace-enclosed initialization list to a vector?

Instead you should cast the initializer list to an initializer_list, like so: Show activity on this post. Template deduction cannot guess that your brace-enclosed initialization list should be a vector. You need to be explicit: vec.emplace_back (std::vector<double> {0.,0.});

What is an initializer list in C++?

Note that Initializer lists is a feature introduced in C++11, so if your C++ version is not up to date, it might not be supported. The below example shows how we can use the C++ Initializer List to store three integers into a vector.


2 Answers

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}); } 
like image 186
Tim Kuipers Avatar answered Sep 18 '22 21:09

Tim Kuipers


Template deduction cannot guess that your brace-enclosed initialization list should be a vector. You need to be explicit:

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

Note that this constructs a vector, and then moves it into the new element using std::vector's move copy constructor. So in this particular case it has no advantage over push_back(). @TimKuipers 's answer shows a way to get around this issue.

like image 32
juanchopanza Avatar answered Sep 18 '22 21:09

juanchopanza