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.
So if my_class
is default constructible, you can do:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.