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.
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.
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.
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.});
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.
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}); }
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.
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