错误:无法使用初始值设定项列表初始化非聚合类型 'vector<string>'

error: non-aggregate type 'vector<string>' cannot be initialized with an initializer list

本文关键字:类型 gt vector 初始化 string lt 列表 错误      更新时间:2023-10-16

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

#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++标准允许从括在大括号中的零个或多个初始元素值列表中初始化向量。那么为什么会出现错误消息呢?

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

该错误来自 clang 编译器,但前提是您编译为 C++98/C++03,因此这意味着您不是编译为 C++11。

P.s - 在我的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. 停止忽略警告