我可以创建一个数组并像这样初始化它:
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);
有没有更好的办法?
当前回答
如果你想要一个与Boost::assign相同的顺序,而不需要创建对Boost的依赖关系,那么下面的代码至少大致类似:
template<class T>
class make_vector {
std::vector<T> data;
public:
make_vector(T const &val) {
data.push_back(val);
}
make_vector<T> &operator,(T const &t) {
data.push_back(t);
return *this;
}
operator std::vector<T>() { return data; }
};
template<class T>
make_vector<T> makeVect(T const &t) {
return make_vector<T>(t);
}
虽然我希望使用它的语法更简洁,但它仍然不是特别糟糕:
std::vector<int> x = (makeVect(1), 2, 3, 4);
其他回答
有各种方法来硬编码一个向量。我将分享一些方法:
通过逐个推入值来初始化 //创建一个空向量 向量< int > vect; vect.push_back (10); vect.push_back (20); vect.push_back (30); 初始化类似数组 Vector <int> Vector {10,20,30}; 从数组初始化 Int arr[] = {10,20,30}; Int n = sizeof(arr) / sizeof(arr[0]); Vector <int> Vector (arr, arr + n); 从另一个向量初始化 Vector <int> vect1{10,20,30}; Vector <int> Vector (Vector 1.begin(), Vector 1.end()));
“我如何创建一个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个元素。
相关的,如果你想在一个快速语句中完全准备好一个向量(例如,立即传递给另一个函数),你可以使用以下方法:
#define VECTOR(first,...) \
([](){ \
static const decltype(first) arr[] = { first,__VA_ARGS__ }; \
std::vector<decltype(first)> ret(arr, arr + sizeof(arr) / sizeof(*arr)); \
return ret;})()
例子函数
template<typename T>
void test(std::vector<T>& values)
{
for(T value : values)
std::cout<<value<<std::endl;
}
示例使用
test(VECTOR(1.2f,2,3,4,5,6));
尽管要小心decltype,但要确保第一个值显然是你想要的。
我使用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
我倾向于宣称
template< typename T, size_t N >
std::vector<T> makeVector( const T (&data)[N] )
{
return std::vector<T>(data, data+N);
}
在一个实用程序头的某处,然后所需要的是:
const double values[] = { 2.0, 1.0, 42.0, -7 };
std::vector<double> array = makeVector(values);