我想知道如何初始化 std::vector
字符串,而不必使用一堆 push_back
在 Visual 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/