简体   繁体   English

push_back向量的新元素

[英]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

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. std::vector有一个名为emplace_back的成员函数,它从向函数提供的参数构造向量中元素类型的新实例。

So if my_class is default constructible, you can do: 因此,如果my_class是默认可构造的,您可以这样做:

my_vector.emplace_back();

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

如果您的类允许默认构造函数:

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

my_vector.push_back({});

甚至更好

my_vector.emplace_back();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM