我可以创建一个数组并像这样初始化它:
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);
有没有更好的办法?
当前回答
如果你想把它放在你自己的课上:
#include <initializer_list>
Vector<Type>::Vector(std::initializer_list<Type> init_list) : _size(init_list.size()),
_capacity(_size),
_data(new Type[_size])
{
int idx = 0;
for (auto it = init_list.begin(); it != init_list.end(); ++it)
_data[idx++] = *it;
}
其他回答
在c++ 0x中,你可以用与数组相同的方式来做这件事,但不是在当前的标准中。
只有语言支持,您可以使用:
int tmp[] = { 10, 20, 30 };
std::vector<int> v( tmp, tmp+3 ); // use some utility to avoid hardcoding the size here
如果你可以添加其他库,你可以尝试boost::assignment:
vector<int> v = list_of(10)(20)(30);
要避免硬编码数组的大小:
// option 1, typesafe, not a compile time constant
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
return N;
}
// option 2, not typesafe, compile time constant
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
// option 3, typesafe, compile time constant
template <typename T, std::size_t N>
char (&sizeof_array( T(&)[N] ))[N]; // declared, undefined
#define ARRAY_SIZE(x) sizeof(sizeof_array(x))
一种方法是使用数组初始化vector
static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
我倾向于宣称
template< typename T, size_t N >
std::vector<T> makeVector( const T (&data)[N] )
{
return std::vector<T>(data, data+N);
}
在一个实用程序头的某处,然后所需要的是:
const double values[] = { 2.0, 1.0, 42.0, -7 };
std::vector<double> array = makeVector(values);
在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};
如果可以,使用现代c++[11,14,17,20,…]):
std::vector<int> ints = {10, 20, 30};
在变长数组上循环或使用sizeof()的旧方法真的很糟糕,而且在精神开销方面完全没有必要。讨厌的东西。