Humam Helfawi
Humam Helfawi

Reputation: 20264

push_back new element to 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

Upvotes: 9

Views: 5004

Answers (5)

ChronoTrigger
ChronoTrigger

Reputation: 8617

If your class allows a default constructor:

my_vector.push_back({});

Upvotes: 2

alphaONE
alphaONE

Reputation: 131

my_vector.push_back({});

or even better

my_vector.emplace_back();

Upvotes: 1

Christian Hackl
Christian Hackl

Reputation: 27528

my_vector.push_back(decltype(my_vector)::value_type());

Upvotes: 1

melak47
melak47

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

fghj
fghj

Reputation: 9394

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

Upvotes: 2

Related Questions