我可以创建一个数组并像这样初始化它:
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);
有没有更好的办法?
当前回答
如果你的编译器支持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所说的那样做。
其他回答
在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()的旧方法真的很糟糕,而且在精神开销方面完全没有必要。讨厌的东西。
如果你的编译器支持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所说的那样做。
“我如何创建一个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个元素。
维克多·塞尔(Viktor Sehr)给出了一个最近的重复问题的答案。对我来说,它很紧凑,在视觉上很吸引人(看起来就像你在“塞”值),不需要c++ 11或第三方模块,并且避免使用额外的(编写的)变量。下面是我如何使用它与一些变化。将来我可能会转而扩展vector和/或va_arg的函数。
// Based on answer by "Viktor Sehr" on Stack Overflow
// https://stackoverflow.com/a/8907356
//
template <typename T>
class mkvec {
public:
typedef mkvec<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
my_type& operator<< (const std::vector<T>& inVector) {
this->data_.reserve(this->data_.size() + inVector.size());
this->data_.insert(this->data_.end(), inVector.begin(), inVector.end());
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
std::vector<int32_t> vec1;
std::vector<int32_t> vec2;
vec1 = mkvec<int32_t>() << 5 << 8 << 19 << 79;
// vec1 = (5, 8, 19, 79)
vec2 = mkvec<int32_t>() << 1 << 2 << 3 << vec1 << 10 << 11 << 12;
// vec2 = (1, 2, 3, 5, 8, 19, 79, 10, 11, 12)