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?
Just thought I'd toss in my $0.02. I tend to declare this:
in a utility header somewhere and then all that's required is:
But I can't wait for C++0x. I'm stuck because my code must also compile in Visual Studio. Boo.
If you want something on the same general order as Boost::assign without creating a dependency on Boost, the following is at least vaguely similar:
While I wish the syntax for using it was cleaner, it's still not particularly awful:
The easiest way to do it is:
In C++11:
Below methods can be used to initialize the vector in c++.
int arr[] = {1, 3, 5, 6}; vector<int> v(arr, arr + sizeof(arr)/sizeof(arr[0]));
vector<int>v; v.push_back(1); v.push_back(2); v.push_back(3);
and so onvector<int>v = {1, 3, 5, 7};
The third one is allowed only in C++11 onwards.
"How do I create an STL vector and initialize it like the above? What is the best way to do so with the minimum typing effort?"
The easiest way to initialize a vector as you've initialized your built-in array is using an initializer list which was introduced in C++11.
ivec is 3 elements in size after Assigning (labeled statement) is executed.