Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Vector of pointers

Tags:

c++

For my latest CS homework, I am required to create a class called Movie which holds title, director, year, rating, actors etc.

Then, I am required to read a file which contains a list of this info and store it in a vector of pointers to Movies.

I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?

Do I just make two vectors - one of pointers and one of Movies and make a one-to-one mapping of the two vectors?

like image 665
xbonez Avatar asked May 17 '10 22:05

xbonez


People also ask

Can I have a vector of pointers?

You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.

What is a vector of pointers in C++?

An ordinary vector encountered in C++ programming, is a vector of objects of the same type. These objects can be fundamental objects or objects instantiated from a class. This article illustrates examples of vector of pointers, to same object type.

What is array of pointers in C?

Declaration of an Array of Pointers in C In simple words, this array is capable of holding the addresses a total of 55 integer variables. Think of it like this- the ary[0] will hold the address of one integer variable, then the ary[1] will hold the address of the other integer variable, and so on.

How do you access vectors of pointers?

Use -> Notation to Access Member Functions From Pointer to a Vector. vector member functions can be called from the pointer to the vector with the -> operator. In this case, we are passing the pointer to the vector to a different function.


1 Answers

It means something like this:

std::vector<Movie *> movies; 

Then you add to the vector as you read lines:

movies.push_back(new Movie(...)); 

Remember to delete all of the Movie* objects once you are done with the vector.

like image 134
Brian R. Bondy Avatar answered Sep 22 '22 10:09

Brian R. Bondy