Reputation: 30635
All the examples I can find of populating a vector using an initializer list look seem to all be creating a vector on the stack:
vector<string> v = {"1","2","3"}
I would like to achieve something like:
vector<string>* v = new vector<string>(){"1","2","3"};
but I get compiler errors. Is it possible to declare a vector on the heap using an initialiser list?
Upvotes: 3
Views: 826
Reputation: 153955
You want to use one of these:
std::vector<std::string>* v = new std::vector<std::string>({"1","2","3"});
std::vector<std::string>* v = new std::vector<std::string>{"1","2","3"};
Upvotes: 1
Reputation: 726849
You need to remove parentheses:
vector<string>* v = new vector<string>{"1","2","3"};
Demo on ideone. Note that this does not work prior to C++11.
Also note that although the vector in your example is created on the stack, it's content is still created on the heap. If you want to have the content stored on the stack as well and the size of the content is known at compile time, use std::array
instead of std::vector
.
Upvotes: 3