I have a vector of pointers to an object:
vector<Foo*> bar;
In a method, I am given an Foo object and need to add it to the vector. This is my current attempt:
void push(const Foo &a){
bar.insert(bar.begin(), a);
}
I know this doesnt work because a was passed as a reference, but I can’t seem to get the pointer for a to add to bar.
How can I add a to the vector bar?
You can’t put an object in a container of pointers.
If you want to put an object in, then you’ll need a container of objects:
In that case, all the objects must be of the same type; if
Foois actually a base class, and you want to store a variety of different derived types, then you’ll need to store pointers.If you want a container of pointers, then you’ll need to put a pointer in it:
In that case, you need to take care with the object’s lifetime, and make sure you don’t use the pointer after the object is destroyed. Smart pointers might be helpful.