Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tersely insert a default-constructed object into a std::vector

Tags:

c++

c++11

stl

All the overloads of std::vector::insert() require a value argument, which is the item to be inserted. However, my item type is complicated and I would rather have an empty-constructed item inserted. That is, I'm looking for a way to do the following without the type name duplication.

std::vector<Long_and_complicated_type_name> v;
...
v.insert(iter, Long_and_complicated_type_name());

The same issue exists for push_back though I'm primarily interested in insert.

like image 834
xan Avatar asked Oct 22 '25 06:10

xan


1 Answers

The std::vector methods emplace and emplace_back can serve that purpose.

template< class... Args > 
iterator emplace( const_iterator pos, Args&&... args );

The forwarded args can be absent, allowing

std::vector<Long_and_complicated_type_name> v;
...
v.emplace(iter);

and even

v.emplace_back();
like image 125
xan Avatar answered Oct 23 '25 18:10

xan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!