Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector<string> initialization with {...} is not allowed in VS2012?

Tags:

c++

string

vector

I was wondering how I can initialize a std::vector of strings, without having to use a bunch of push_back's in Visual Studio Ultimate 2012.


I've tried vector<string> test = {"hello", "world"}, but that gave me the following error:

Error: initialization with '{...}' is not allowed for an object of type "std::vector<std::string, std::allocator<std::string>>


  • Why do I receive the error?
  • Any ideas on what I can do to store the strings?
like image 600
randomname Avatar asked Jan 10 '23 12:01

randomname


1 Answers

The problem

You'll have to upgrade to a more recent compiler version (and standard library implementation), if you'd like to use what you have in your snippet.

VS2012 doesn't support std::initializer_list, which means that the overload among std::vector's constructors, that you are trying to use, simply doesn't exist.

In other words; the example cannot be compiled with VS2012.

  • msdn.com - Support For C++11 Features (Modern C++)

Potential Workaround

Use an intermediate array to store the std::strings, and use that to initialize the vector.

std::string const init_data[] = {
  "hello", "world"
};

std::vector<std::string> test (std::begin (init_data), std::end (init_data));
like image 197
Filip Roséen - refp Avatar answered Jan 21 '23 01:01

Filip Roséen - refp