How do we initialize a std::vector in a class constructor in c++?
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;
};
Syntax for Vectors in C++Every new vector must be declared starting with the vector keyword. This is followed by angle brackets which contain the the type of data the vector can accept like strings, integers, and so on. Lastly, the vector name - we can call this whatever we want.
First, myVector
will be initialized, even if you do nothing,
since it has non-trivial constructors. If you want to
initialize it given a pointer to a sequence of int
, you'll
also have to know the length. 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()
.)
EDIT:
Just to make it perfectly clear: just an int*
doesn't provide
enough information to do anything. An int*
points to the
first element of a C style array; you also need some way of
finding the end: an element count, an end pointer, etc. In
special cases, other techniques can be used; i.e. 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 ) )
. These are special cases, however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With