[英]How do we initialize a std::vector in a class constructor in C++?
How do we initialize a std::vector in a class constructor in c++? 我们如何在c ++中的类构造函数中初始化std :: vector?
class MyClass
{
public:
MyClass( int p_Var1, int* p_Vector ) : Var1( p_Var1 ) //, Initialize std::vector - MyVector with p_Vector
{
};
~MyClass( void );
private:
int Var1;
std::vector< int > MyVector;
};
First, myVector
will be initialized, even if you do nothing, since it has non-trivial constructors. 首先, myVector
将被初始化,即使你什么都不做,因为它有非平凡的构造函数。 If you want to initialize it given a pointer to a sequence of int
, you'll also have to know the length. 如果要在给定指向int
序列的指针的情况下初始化它,您还必须知道长度。 If you have both a pointer and the length, you can do: 如果你有一个指针和长度,你可以这样做:
: myVector( pInitialValues, pInitialValues + length )
Alternatively (and more idiomatically), you'll let the caller do the addition, and have the constructor take two pointers, a begin and an end: 或者(并且更具惯用性),您将让调用者执行添加,并让构造函数采用两个指针,即开始和结束:
: myVector( pBegin, pEnd )
(If the caller is using C++11, he can obtain these from a C style array using std::begin()
and std::end()
.) (如果调用者正在使用C ++ 11,他可以使用std::begin()
和std::end()
从C样式数组中获取这些。)
EDIT: 编辑:
Just to make it perfectly clear: just an int*
doesn't provide enough information to do anything. 只是为了使它完全清楚:只是一个int*
没有提供足够的信息来做任何事情。 An int*
points to the first element of a C style array; int*
指向C样式数组的第一个元素; you also need some way of finding the end: an element count, an end pointer, etc. In special cases, other techniques can be used; 你还需要一些方法来找到结尾:元素计数,结束指针等。在特殊情况下,可以使用其他技术; ie if the C style array contains only non-negative numbers, you could use -1
as a sentinal, and something like : myVector( pVector, std::find( pVector, NULL, -1 ) )
. 即如果C样式数组仅包含非负数,则可以使用-1
作为sentinal,例如: myVector( pVector, std::find( pVector, NULL, -1 ) )
。 These are special cases, however. 然而,这些是特殊情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.