问题复现
#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。