首页 > 解决方案 > 像这样初始化 int 向量有什么问题:vectorv1 = {1, 2, 3, 4}?

问题描述

当我像这样在 C++ 中初始化一个向量时:

#include <string>
#include <vector>
using std::vector;
using std::string;
int main() {

  vector<int> v1 = {1, 2, 3, 4};
  return 0;
}

我收到了这个错误:

prog1.cpp:8:15: error: non-aggregate type 'vector<int>' cannot be initialized with an initializer list
  vector<int> v1 = {1, 2, 3, 4};
              ^    ~~~~~~~~~~~~
1 error generated.

知道为什么会这样吗?

标签: c++vector

解决方案


-std=version初始化列表是从 C++ 11 开始引入的,因此如果您使用旧标准进行默认编译,则需要在编译 ( ) 时指定该(或更高)版本。


推荐阅读