joncodo
joncodo

Reputation: 2328

How to save collections of objects and use them in c++ vector

I need to use a vector that has a type of MyClass.

vector<MyClass> vMyClass;
vMyClass.Push_Back(new MyClass);

This does not seem to work for me. What is going wrong? I am trying to simulate a List like in C#.

I then need to perform an action on all items in the list. Like in C# foreach item in vMyClass.

I have looked everywhere for a simple example of this and have had no luck. Please help.

Upvotes: 0

Views: 62

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

new MyClass returns a pointer to a MyClass, but your vector contains objects, not pointers.

Try

vMyClass.push_back(MyClass());

or, if you need dynamic memory

vector<MyClass*> vMyClass;

with your version. Note the all-lower-case push_back.

Upvotes: 4

Related Questions