我可以创建一个数组并像这样初始化它:
int a[] = {10, 20, 30};
我如何创建一个std::vector和初始化它同样优雅?
我知道的最好的方法是:
std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);
有没有更好的办法?
我可以创建一个数组并像这样初始化它:
int a[] = {10, 20, 30};
我如何创建一个std::vector和初始化它同样优雅?
我知道的最好的方法是:
std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);
有没有更好的办法?
当前回答
c++ 11:
static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));
其他回答
c++ 11:
static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));
c++ 11:
#include <vector>
using std::vector;
...
vector<int> vec1 { 10, 20, 30 };
// or
vector<int> vec2 = { 10, 20, 30 };
使用Boost list_of:
#include <vector>
#include <boost/assign/list_of.hpp>
using std::vector;
...
vector<int> vec = boost::assign::list_of(10)(20)(30);
使用Boost赋值:
#include <vector>
#include <boost/assign/std/vector.hpp>
using std::vector;
...
vector<int> vec;
vec += 10, 20, 30;
传统的STL:
#include <vector>
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
带有通用宏的常规STL:
#include <vector>
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0])
#define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, ARRAY_END(arr));
带有矢量初始化宏的常规STL:
#include <vector>
#define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0])
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec INIT_FROM_ARRAY(arr);
在C++ 11之前:
方法1
vector<int> v(arr, arr + sizeof(arr)/sizeof(arr[0]));
方法2
vector<int>v;
v.push_back(SomeValue);
下面的c++ 11也是可能的
vector<int>v = {1, 3, 5, 7};
我们也可以这样做
vector<int>v {1, 3, 5, 7}; // Notice .. no "=" sign
对于c++ 17以后,我们可以省略类型
vector v = {1, 3, 5, 7};
我使用va_arg构建自己的解决方案。该解决方案是c++ 98兼容的。
#include <cstdarg>
#include <iostream>
#include <vector>
template <typename T>
std::vector<T> initVector (int len, ...)
{
std::vector<T> v;
va_list vl;
va_start(vl, len);
for (int i = 0; i < len; ++i)
v.push_back(va_arg(vl, T));
va_end(vl);
return v;
}
int main ()
{
std::vector<int> v = initVector<int> (7,702,422,631,834,892,104,772);
for (std::vector<int>::const_iterator it = v.begin() ; it != v.end(); ++it)
std::cout << *it << std::endl;
return 0;
}
Demo
一种方法是使用数组初始化vector
static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );