user997112
user997112

Reputation: 30635

vector<string> on heap, using an initializer list?

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

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

You want to use one of these:

  1. std::vector<std::string>* v = new std::vector<std::string>({"1","2","3"});
  2. std::vector<std::string>* v = new std::vector<std::string>{"1","2","3"};

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions