Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate a new STL vector

Tags:

c++

stl

I have a situation where I have a pointer to an STL vector.

So like

vector<MyType*>* myvector;

I have to set this pointer to NULL in the constructor and then lazy load when the property is touched.

How can I instantiate this to a new instance of a vector?

like image 633
np-hard Avatar asked Dec 10 '22 20:12

np-hard


1 Answers

Assuming you define vector correctly:

vector<int>*   myvector;  // Note vector must be parametrized with a type.
                          // There is no such thing as a a naked vector.

Initialize to NULL

myclass::myclass()
   :myvector(NULL)       // You can use 0 here but I still like NULL because it
{}                       // gives me more information. Waiting for the new keyword.

Instantiate on first use:

myvectr = new vector<int>(100); // reserve some space as appropriate

But you should not have a raw pointer as a member to your class (unless there is a very good reason). You will need to write your own copy constructor and assignment operator.

Or alternatively you can wrap 'myvector' with a smart pointer. Or even better make it a normal vector. There is no real need to make it a pointer.

like image 82
Martin York Avatar answered Dec 21 '22 12:12

Martin York