3

嗨,我是 C++ 的新手,我无法使用 {} 初始化向量,即使代码是用书复制的。例如,当我做这些

vector <string> articles {"a", "an", "the"};

vector <string> articles = {"a", "an", "the"};

我分别收到这些错误消息:

Error: expected a ";"

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

有人会帮我吗?我相信这应该是一个我无法发现的简单错误。

4

1 回答 1

2

uniform initialization从 C++11 开始引入,您应该使用支持此新功能的最新编译器。

如果您的编译器不支持此功能,您可以尝试以下操作:

string arrOfString[3] =  {"a", "an", "the"};
vector<string> articles(arrOfString, arrOfString +3);

编辑

使用 MSVC11,您可以执行以下操作(由 @chris 提供):

string arrOfString[3] =  {"a", "an", "the"};
vector<string> articles(std::begin(arrOfString), std::end(arrOfString));
于 2013-05-24T02:48:47.123 回答