我可以创建一个数组,并像这样初始化它。
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,你可以简单地做到。
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);
或者。
#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
...
std::vector<int> v;
v += 1, 2, 3, 4;
但请记住,这有一定的开销(基本上,list_of
构建了一个std::deque
的外壳),所以对于性能关键型的代码,你最好按Yacoby说的做。
在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))