4

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?
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
randomname
  • 265
  • 1
  • 9
  • 20

2 Answers2

9

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.


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));
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
0

1. Why do I receive the error? Visual Studio 2012 doesn't support list initialization before the 2012 November update according to this question.

2.Any ideas on what I can do to store the strings?

Using push_back() is a totally valid solution. Example:

#include<vector>
#include <string>
using namespace std;
int main()
{
    vector<string> test;
    test.push_back("hello");
    test.push_back("world");
    for(int i=0; i<test.size(); i++)
     cout<<test[i]<<endl;
    return 0;
}
Dávid Tóth
  • 2,788
  • 1
  • 21
  • 46