c++ - VS2012 中不允许使用 {...} 进行 vector <字符串> 初始化?

标签 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>>


  • 为什么我会收到错误消息?
  • 关于如何存储字符串有什么想法吗?

最佳答案

问题

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

VS2012 doesn't support std::initializer_list,这意味着您尝试使用的 std::vector 构造函数中的重载根本不存在。

换句话说;该示例无法使用 VS2012 进行编译。


可能的解决方法

使用中间数组 来存储std::string,并使用它来初始化 vector 。

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

std::vector<std::string> test (std::begin (init_data), std::end (init_data));

关于c++ - VS2012 中不允许使用 {...} 进行 vector <字符串> 初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23977264/

相关文章:

c++ - 为什么我们不能像在 C++ 中输入数组那样输入 vector ?

c++ - .begin 左边必须有类/结构/union

C++ 模板方法前向声明

c++ - 使用 unordered_map 移动构造函数

java - 电话号码的 SimpleDateFormat 意外成功

C: strtok 将所有值返回给 printf,只返回一半值给数组

c++ - 对一对 vector 进行排序

C++命令行程序设计UI?

c - 如何从字符串类型行中提取char类型元素并添加到c中的列表中

c++ - 为什么 libc++ std::vector 在内部保留三个指针而不是一个指针和两个大小?