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?
In C++0x you will be able to do it in the same way that you did with an array, but not in the current standard.
With only language support you can use:
If you can add other libraries you could try boost::assignment:
To avoid hardcoding the size of an array:
B. Stroustrup describes a nice way to chain operations in 16.2.10 Selfreference on page 464 in the C++11 edition of the Prog. Lang. where a function returns a reference, here modified to a vector. This way you can chain like
v.pb(1).pb(2).pb(3);
but may be too much work for such small gains.If you don't want to use boost, but want to enjoy syntax like
just include this chunk of code
you can do that using boost::assign.
detail here
If the array is:
If your compiler supports C++11, you can simply do:
This is available in GCC as of version 4.4. Unfortunately, VC++ 2010 seems to be lagging behind in this respect.
Alternatively, the Boost.Assign library uses non-macro magic to allow the following:
Or:
But keep in mind that this has some overhead (basically,
list_of
constructs astd::deque
under the hood) so for performance-critical code you'd be better off doing as Yacoby says.