我可以创建一个数组并像这样初始化它:
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);
有没有更好的办法?
当前回答
最简单的方法是:
vector<int> ints = {10, 20, 30};
其他回答
“我如何创建一个STL向量并像上面那样初始化它?用最少的打字工作量做到这一点的最佳方法是什么?”
在初始化内置数组时,初始化vector最简单的方法是使用c++ 11中引入的初始化列表。
// Initializing a vector that holds 2 elements of type int.
Initializing:
std::vector<int> ivec = {10, 20};
// The push_back function is more of a form of assignment with the exception of course
//that it doesn't obliterate the value of the object it's being called on.
Assigning
ivec.push_back(30);
执行赋值(标签语句)后,ivec大小为3个元素。
如果你想把它放在你自己的课上:
#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++ 11:
static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));
如果可以,使用现代c++[11,14,17,20,…]):
std::vector<int> ints = {10, 20, 30};
在变长数组上循环或使用sizeof()的旧方法真的很糟糕,而且在精神开销方面完全没有必要。讨厌的东西。
你可以使用boost::assign:
vector<int> values;
values += 1,2,3,4,5,6,7,8,9;
详情在这里。