使用硬编码元素初始化 std::vector 的最简单方法是什么?

问题描述:

我可以创建一个数组并像这样初始化它:

I can create an array and initialize it like this:

int a[] = {10, 20, 30};

如何创建一个 std::vector 并以同样优雅的方式初始化它?

How do I create a std::vector and initialize it similarly elegant?

我所知道的最好方法是:

The best way I know is:

std::vector<int> ints;

ints.push_back(10);
ints.push_back(20);
ints.push_back(30);

有更好的方法吗?

一种方法是使用数组来初始化向量

One method would be to use the array to initialize the vector

static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );