错误:无法使用初始化列表初始化非聚合类型"vector <string>"

Tho*_*hor 1 c++ vector c++11

我是C++的新手,正在尝试学习矢量的概念.但是,当我运行以下代码时:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main(){

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

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

IDE输出错误消息:

error: non-aggregate type 'vector<string>' cannot be initialized with an initializer list
    vector<string> vs1 = {"a", "an", "the"};
                   ^     ~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

我认为新的C++标准允许从花括号中包含的零个或多个初始元素值列表中初始化一个向量.那么为什么错误信息呢?

Ps - 在我的NetBean IDE上使用auto(也在c ++ 11中引入)很好

Jon*_*ely 6

该错误来自clang编译器,但仅当您编译为C++ 98/C++ 03时,这意味着您不编译为C++ 11.

Ps - 在我的NetBean IDE上使用auto(也在c ++ 11中引入)很好

(你的IDE并不重要,它不是编译代码的编译器所做的).

Clang允许auto在C++ 98模式下,但会发出警告:

prog.cc:8:5: warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]

所以你需要

  1. 启用C++ 11模式

  2. 停止忽略警告