在VS2012中不允许使用{...}进行vector <string>初始化?

ran*_*ame 3 c++ string vector

我想知道如何初始化一个std::vector字符串,而不必push_backVisual Studio Ultimate 2012中使用一堆.


我试过了vector<string> test = {"hello", "world"},但这给了我以下错误:

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


  • 为什么我收到错误?
  • 关于我可以做什么来存储字符串的任何想法?

Fil*_*efp 8

问题

如果您想使用代码段中的内容,则必须升级到更新的编译器版本(以及标准库实现).

VS2012 不支持 std::initializer_list,这意味着std::vector您尝试使用的构造函数之间的重载根本不存在.

换一种说法; 该示例无法使用VS2012进行编译.


潜在的解决方法

使用中间数组来存储std::strings,并使用它来初始化向量.

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

std::vector<std::string> test (std::begin (init_data), std::end (init_data));
Run Code Online (Sandbox Code Playgroud)