Push_back new item in vector

I have this vector:

std::vector<my_class> my_vector; 

I want to add a new element with a standard constructor. So I write:

 my_vector.push_back(my_class()); 

is there any way to do this without mentioning the type directly ?. For example, something like:

  my_vector.push_back(auto()); // imaginary code 
+6
source share
5 answers

std::vector has a member function called emplace_back , which builds a new instance of the vector type of the element in the vector from the arguments provided to the function.

So, if my_class is constructive by default, you can do:

 my_vector.emplace_back(); 
+13
source

my_vector.resize(my_vector.size() + 1);

+2
source

If your class allows the default constructor:

 my_vector.push_back({}); 
+2
source
 my_vector.push_back(decltype(my_vector)::value_type()); 
+1
source

my_vector.push_back({});

or even better

my_vector.emplace_back();

+1
source

All Articles