how to fill a vector with objects using pointers

2019-09-08 15:41发布

问题:

I have an assignment where I have to create a vector and fill it with objects. I found this code:

Vehicle * v = NULL;
vector<Vehicle*> *highway;
highway = new vector<Vehicle*>;

I understand the first line where it creates a pointer named v that is empty and points at the object Vehicle.

Can you please explain to me how the other 2 lines work and why is it using pointers when creating the vector?

回答1:

Here is a brief explanation line by line:

Vehicle * v = NULL;

define a pointer v of type Vehicle and initialize it to NULL.

vector<Vehicle*> *highway;

define a pointer highway of type vector<Vehicle*>.

highway = new vector<Vehicle*>;

dynamically allocate vector<Vehicle*> and assign it to vector highway.

Have a look at std::vector and make sure you understand why the last two lines doesn't make much sense.

Now, to answer the question:

How to fill a vector with objects using pointers?

To fill the dynamically allocated vector, you could write:

highway->push_back(Vehicle_Element);    


回答2:

First line: You create a pointer of type "Vehicle". It is not pointing at a object, because it is NULL. It points to nothing. You have to create an object like:

Vehicle* v = new Vehicle;

Second line: Same construction like the first line: You create a pointer of type "vector". Now its not pointing anywhere. If you create (see third line) it than you have a pointer to a vector which has pointers to Vehicle objects.

Third line: With this line you create the vector pointer.