So I’m new to c++ and programming in general, and in some of my assignments I need to store objects that I create in a vector and I always used this method:
std::vector<Class_Name> Classes;
Class_Name c1,c2,c3,c4;
Classes.push_back(c1);
Classes.push_back(c2);
Classes.push_back(c3);
Classes.push_back(c4);
But it looks kind of ugly.
I then found out that this method is pretty inefficient and creates an unnecessary copy of the object and I then found out about emplace_back.
Got to this:
std::vector<Class_Name> Classes;
Classes.emplace_back(args);
This is nice and all but I was thinking if there was a way to create an object and, with the help of some magic in the constructor body, have it be put into a vector.
Something like this(?):
class Class_Name{
...
std::vector<Class_Name> Classes;
public:
Class_Name(args) {Classes.push_back(c1)} // just imagine c1 is the object to be
...
};
In short, is emplace_back the most efficient method and, if someone understood what I was trying to show with the constructor, is it possible to do my example/is it worth it?
Totenkopf is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.