I can create an array and initialize it like this:
int a[] = {10, 20, 30};
How do I create a std::vector
and initialize it similarly elegant?
The best way I know is:
std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);
Is there a better way?
For God's sake, use the modern C++[11,14,17,...] way:
The old way of looping over a variable-length array or using
sizeof()
is truly terrible on the eyes and completely unnecessary in terms of mental overhead. Yuck.A more recent duplicate question has this answer by Viktor Sehr. For me, it is compact, visually appealing (looks like you are 'shoving' the values in), doesn't require c++11 or a third party module, and avoids using an extra (written) variable. Below is how I am using it with a few changes. I may switch to extending the function of vector and/or va_arg in the future intead.
If your compiler supports Variadic macros (which is true for most modern compilers), then you can use the following macro to turn vector initialization into a one-liner:
With this macro, you can define an initialized vector with code like this:
This would create a new vector of ints named my_vector with the elements 1, 2, 3, 4.
Related, you can use the following if you want to have a vector completely ready to go in a quick statement (e.g. immediately passing to another function):
example function
example use
though be careful about the decltype, make sure the first value is clearly what you want.
Before C++ 11 :
Method 1=>
Method 2 =>
C++ 11 onward below is also possible
To compile use: