我可以创建一个数组并像这样初始化它:
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 中可用 as of version 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++ - 用硬编码元素初始化 std::vector 的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2236197/