Reputation: 20264
I have this vector:
std::vector<my_class> my_vector;
I want to add new item with the default constructor. So, I write:
my_vector.push_back(my_class());
is there way to do it without mention the type directly?. For example something like:
my_vector.push_back(auto()); // imaginary code
Upvotes: 9
Views: 5004
Reputation: 8617
If your class allows a default constructor:
my_vector.push_back({});
Upvotes: 2
Reputation: 4850
std::vector
has a member function called emplace_back
which constructs a new instance of the vector's element type in the vector, from the arguments provided to the function.
So if my_class
is default constructible, you can do:
my_vector.emplace_back();
Upvotes: 18