问题复现
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> msg = {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
for (const string& word : msg)
{
cout << word << " ";
}
cout << endl;
}
运行代码结果
g++ hello.cpp -o hello
hello.cpp:9:20: error: non-aggregate type 'vector<std::string>' (aka 'vector<basic_string<char, char_traits<char>, allocator<char> > >') cannot be initialized with an initializer list
vector<string> msg = {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
hello.cpp:11:29: warning: range-based for loop is a C++11 extension [-Wc++11-extensions]
for (const string& word : msg)
解决方法
使用这个编译命令:g++ -std=c++11 hello.cpp -o hello
原因:列表初始化vector对象,属于C++11标准。因此,在使用g++进行编译的时候,需要特别开启C++11标准编译选项:-std=c++11。
文章描述了一段C++代码在尝试用初始化列表初始化vector时遇到的错误。问题在于编译器未启用C++11标准,导致无法识别这种语法。解决方案是使用g++编译器时添加标志`-std=c++11`,以启用C++11标准支持。

2558

被折叠的 条评论
为什么被折叠?



