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?
Starting with:
If you don't have a C++11 compiler and you don't want to use boost:
If you don't have a C++11 compiler and can use boost:
If you do have a C++11 compiler:
I build my own solution using
va_arg
. This solution is C98 compliant.Demo
There are a lot of good answers here, but since I independently arrived at my own before reading this, I figured I'd toss mine up here anyway...
Here's a method that I'm using for this which will work universally across compilers and platforms:
Create a struct or class as a container for your collection of objects. Define an operator overload function for <<.
You can create functions which take your struct as a parameter, e.g.:
Then, you can call that function, like this:
That way, you can build and pass a dynamically sized collection of objects to a function in one single clean line!
For vector initialisation -
can be done if you have c++11 compiler.
Else, you can have an array of the data and then use a for loop.
Apart from these, there are various other ways described above using some code. In my opinion, these ways are easy to remember and quick to write.
In C++11:
Using boost list_of:
Using boost assign:
Conventional STL:
Conventional STL with generic macros:
Conventional STL with a vector initializer macro: