Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

push_back new element to vector

Tags:

c++

c++11

vector

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
like image 880
Humam Helfawi Avatar asked Oct 25 '15 16:10

Humam Helfawi


1 Answers

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();
like image 110
melak47 Avatar answered Nov 10 '22 16:11

melak47