我可以创建一个数组并像这样初始化它:
int a[] = {10, 20, 30};
如何创建一个 std::vector
并以同样优雅的方式初始化它?
我知道的最好方法是:
std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);
有没有更好的办法?
tr1::array
很有用,因为普通数组不提供 STL 容器的接口
如果您的编译器支持 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 所说的那样做。
一种方法是使用数组来初始化向量
static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
static
或 const
也可以正常工作,但是它们都更明确地说明了应该如何使用它,并允许编译器进行额外的优化。
如果可以,请使用现代 C++[11,14,17,20,...] 方式:
std::vector<int> ints = {10, 20, 30};
循环可变长度数组或使用 sizeof()
的旧方法在视觉上确实很糟糕,并且在精神开销方面完全没有必要。呸。
={}
?
=
在 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))
int another[size_of_array(array)]
,而您可以执行 int another[ARRAY_SIZE(array)]
。
sizeof
表达式之外,我们实际上并不希望该函数用于其他任何东西。虽然您实际上可以提供定义,但要正确执行,需要静态分配数组并返回对它的引用,下一个问题是数组的值是什么? (另请注意,这意味着函数实例化的每个类型/大小组合都有一个数组!)由于它没有合理的用途,我宁愿避免它。
在 C++11 中:
#include <vector>
using std::vector;
...
vector<int> vec1 { 10, 20, 30 };
// or
vector<int> vec2 = { 10, 20, 30 };
使用增强 list_of
:
#include <vector>
#include <boost/assign/list_of.hpp>
using std::vector;
...
vector<int> vec = boost::assign::list_of(10)(20)(30);
使用 Boost 分配:
#include <vector>
#include <boost/assign/std/vector.hpp>
using std::vector;
...
vector<int> vec;
vec += 10, 20, 30;
常规 STL:
#include <vector>
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
带有通用宏的传统 STL:
#include <vector>
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0])
#define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, ARRAY_END(arr));
带有向量初始化器宏的传统 STL:
#include <vector>
#define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0])
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec INIT_FROM_ARRAY(arr);
std::begin
和 std::end
,因此向量也可以像 static const int arr[] = {10,20,30}; vector<int> vec(begin(arr), end(arr));
一样初始化。
我倾向于声明
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);
const T (&data)[N]
部分吗?您的调用 makeVector(values)
中如何推导出数组的大小?
在 C++ 11 之前:
方法一
vector<int> v(arr, arr + sizeof(arr)/sizeof(arr[0]));
方法二
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};
从...开始:
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};
对于向量初始化 -
vector<int> v = {10, 20, 30}
如果您有 C++11 编译器,则可以完成。
否则,您可以拥有一个数据数组,然后使用 for 循环。
int array[] = {10,20,30}
for(unsigned int i=0; i<sizeof(array)/sizeof(array[0]); i++)
{
v.push_back(array[i]);
}
除此之外,在之前的答案中还使用一些代码描述了其他各种方法。在我看来,这些方式很容易记住并且写起来很快。
最简单的方法是:
vector<int> ints = {10, 20, 30};
如果您的编译器支持 Variadic macros(对于大多数现代编译器都是如此),那么您可以使用以下宏将向量初始化转换为单行:
#define INIT_VECTOR(type, name, ...) \
static const type name##_a[] = __VA_ARGS__; \
vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
使用此宏,您可以使用如下代码定义初始化向量:
INIT_VECTOR(int, my_vector, {1, 2, 3, 4});
这将创建一个名为 my_vector 的新整数向量,其元素为 1、2、3、4。
我使用 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;
}
如果您不想使用 Boost,但想享受类似的语法
std::vector<int> v;
v+=1,2,3,4,5;
只包含这段代码
template <class T> class vector_inserter{
public:
std::vector<T>& v;
vector_inserter(std::vector<T>& v):v(v){}
vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
};
template <class T> vector_inserter<T> operator+=(std::vector<T>& v,const T& x){
return vector_inserter<T>(v),x;
}
((((v+=1),2),3),4),5)
这是它的工作原理:首先,vector<T> += T
返回一个vector_inserter,我们称之为vi
封装原始向量然后vi,T
将T添加到vi
封装并返回它的原始向量self 以便我们可以再次执行 vi,T
。
在 C++11 中:
static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));
vector<int> arr = {10, 20, 30};
。
一个较新的重复问题有 this answer by 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)
你可以使用 boost::assign 来做到这一点:
vector<int> values;
values += 1,2,3,4,5,6,7,8,9;
+=
是否将 1,2,3,4.. 附加到值的末尾,还是 添加 1 到第一个元素,2 到第二个元素,3 到第三个元素(像这样的语法应该在类似 MATLAB 的语言中)
以下方法可用于在 C++ 中初始化向量。
int arr[] = {1, 3, 5, 6};向量
第三个只允许在 C++11 以后。
这里有很多很好的答案,但由于我在阅读本文之前独立得出了自己的答案,所以我想无论如何我都会把我的答案扔在这里......
这是我为此使用的一种方法,它将在编译器和平台上通用:
创建一个结构或类作为对象集合的容器。为 <<
定义一个运算符重载函数。
class MyObject;
struct MyObjectList
{
std::list<MyObject> objects;
MyObjectList& operator<<( const MyObject o )
{
objects.push_back( o );
return *this;
}
};
您可以创建将您的结构作为参数的函数,例如:
someFunc( MyObjectList &objects );
然后,您可以调用该函数,如下所示:
someFunc( MyObjectList() << MyObject(1) << MyObject(2) << MyObject(3) );
这样,您可以在一条干净的行中构建动态大小的对象集合并将其传递给函数!
如果您想要与 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);
typedef std::vector<int> arr;
arr a {10, 20, 30}; // This would be how you initialize while defining
编译使用:
clang++ -std=c++11 -stdlib=libc++ <filename.cpp>
// Before C++11
// I used following methods:
// 1.
int A[] = {10, 20, 30}; // original array A
unsigned sizeOfA = sizeof(A)/sizeof(A[0]); // calculate the number of elements
// declare vector vArrayA,
std::vector<int> vArrayA(sizeOfA); // make room for all
// array A integers
// and initialize them to 0
for(unsigned i=0; i<sizeOfA; i++)
vArrayA[i] = A[i]; // initialize vector vArrayA
//2.
int B[] = {40, 50, 60, 70}; // original array B
std::vector<int> vArrayB; // declare vector vArrayB
for (unsigned i=0; i<sizeof(B)/sizeof(B[0]); i++)
vArrayB.push_back(B[i]); // initialize vArrayB
//3.
int C[] = {1, 2, 3, 4}; // original array C
std::vector<int> vArrayC; // create an empty vector vArrayC
vArrayC.resize(sizeof(C)/sizeof(C[0])); // enlarging the number of
// contained elements
for (unsigned i=0; i<sizeof(C)/sizeof(C[0]); i++)
vArrayC.at(i) = C[i]; // initialize vArrayC
// A Note:
// Above methods will work well for complex arrays
// with structures as its elements.
在编写测试时创建一个内联向量而不定义变量是非常方便的,例如:
assert(MyFunction() == std::vector<int>{1, 3, 4}); // <- this.
“我如何创建一个 STL 向量并像上面那样初始化它?以最少的打字工作量最好的方法是什么?”
初始化内置数组时初始化向量的最简单方法是使用 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 个元素。
有多种方法可以对向量进行硬编码。我将分享几个方法:
通过一个一个推入值来初始化 // 创建一个空向量 vector
auto vect2 = vect1;
或 vector<int> vect2 = vect1
,对吗?
如果数组是:
int arr[] = {1, 2, 3};
int len = (sizeof(arr)/sizeof(arr[0])); // finding length of array
vector < int > v;
v.assign(arr, arr+len); // assigning elements from array to vector
(std::v).assign(arr, arr + len);
,而 namespace std
中没有 v
。还是您的意思是std::vector<int> v; v.assign(...);
?
len = std::size(arr);
。它在引擎盖下做同样的事情。
相关的,如果你想让一个向量完全准备好进入一个快速语句(例如立即传递给另一个函数),你可以使用以下内容:
#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,但请确保第一个值显然是您想要的。
B. Stroustrup 在 C++11 版 Prog 的第 464 页的 16.2.10 Selfreference 中描述了一种链接操作的好方法。朗。其中一个函数返回一个引用,这里修改为一个向量。通过这种方式,您可以像 v.pb(1).pb(2).pb(3);
一样进行链接,但对于这么小的收益来说可能工作量太大。
#include <iostream>
#include <vector>
template<typename T>
class chain
{
private:
std::vector<T> _v;
public:
chain& pb(T a) {
_v.push_back(a);
return *this;
};
std::vector<T> get() { return _v; };
};
using namespace std;
int main(int argc, char const *argv[])
{
chain<int> v{};
v.pb(1).pb(2).pb(3);
for (auto& i : v.get()) {
cout << i << endl;
}
return 0;
}
1 2 3
最简单、符合人体工程学的方式(使用 C++ 11 或更高版本):
auto my_ints = {1,2,3};
my_ints
推断为 std::initializer_list<int>
而不是 std::vector<int>
吗?
如果您想在自己的课程中使用它:
#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;
}
this->vect = {};
?std::vector<T> vector;
std::vector<int> v = {1, 2, 3, 4};
感到好奇,将调用向量的initializer list constructor
进行这种初始化,它的文档可以在C++ 11
section 中找到。