2016-02-05 37 views
1

我是C++的新手,正在尝试学习矢量的概念。然而,当我运行代码如下:错误:非聚合类型'矢量<string>'无法用初始化程序列表初始化

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

int main(){ 

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

    return 0; 
} 

IDE将输出错误消息:

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

我认为新的C++标准允许的载体的初始化从零个或多个初始元素的值的列表用大括号括起来。那么为什么错误信息呢?

诗 - 使用自动(这也是在C++ 11引入的)是我的NetBean IDE精细

+3

你使用什么编译器(版本)? –

+3

使用'-std = C++ 11'或'-std = C++ 14'编译器开关 –

+1

您可能需要'#include ' – Brian

回答

6

该错误来自铛编译器,但只有当你编译为C++ 98/C++ 03,所以这意味着你不会编译为C++ 11。 (你的IDE并不重要,它不是编译代码的东西,编译器会这么做)。

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

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

所以,你需要

  1. 启用C++ 11模式

  2. 不要忽视警告