我可以创建一个数组并像这样初始化它:
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);
有没有更好的办法?
当前回答
开始:
int a[] = {10, 20, 30}; //I'm assuming 'a' is just a placeholder
如果你没有c++ 11编译器,也不想使用Boost:
const int a[] = {10, 20, 30};
const std::vector<int> ints(a, a+sizeof(a)/sizeof(int)); //Make it const if you can
如果你没有c++ 11编译器,可以使用Boost:
#include <boost/assign.hpp>
const std::vector<int> ints = boost::assign::list_of(10)(20)(30);
如果你有c++ 11编译器:
const std::vector<int> ints = {10,20,30};
其他回答
你可以使用boost::assign:
vector<int> values;
values += 1,2,3,4,5,6,7,8,9;
详情在这里。
如果你的编译器支持c++ 11,你可以简单地这样做:
std::vector<int> v = {1, 2, 3, 4};
这在GCC 4.4版中可用。不幸的是,vc++ 2010在这方面似乎落后了。
或者是Boost。Assign库使用非宏魔术来允许以下:
#include <boost/assign/list_of.hpp>
...
std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);
Or:
#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
...
std::vector<int> v;
v += 1, 2, 3, 4;
但请记住,这有一些开销(基本上,list_of在底层构造了一个std::deque),因此对于性能关键的代码,您最好按照Yacoby所说的那样做。
我使用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
“我如何创建一个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;
}