嗨,我是 C++ 新手,即使代码是随书复制的,我也无法使用 {} 初始化 vector 。例如,当我做这些
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>>"
有人会帮我吗?我相信这应该是一个我无法发现的简单错误。
最佳答案
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));
关于c++ - vector 不能被 {} 初始化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16726919/