Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between insert and emplace for vector in C++ [duplicate]

Tags:

c++

vector

Apart from single insertion using emplace and multiple insertion using insert in vector, is there any other difference in their implementation?

As in both cases inserting any element will shift all other elements.

like image 566
Sandeepjn Avatar asked Mar 27 '13 12:03

Sandeepjn


People also ask

Is emplace better than insert?

Both are used to add an element in the container. The advantage of emplace is, it does in-place insertion and avoids an unnecessary copy of object. For primitive data types, it does not matter which one we use. But for objects, use of emplace() is preferred for efficiency reasons.

What is the difference between a vector and an insert?

The key difference between insertion and replacement vectors is that the insertion vector has the ability to insert moderate lengths of foreign DNA while replacement vector has the ability to accommodate larger lengths of foreign DNA.

What is emplace in vector?

The vector::emplace() is an STL in C++ which extends the container by inserting a new element at the position. Reallocation happens only if there is a need for more space. Here the container size increases by one. Syntax: template iterator vector_name.

What is the difference between emplace and push?

While push() function inserts a copy of the value or the parameter passed to the function into the container at the top, the emplace() function constructs a new element as the value of the parameter and then adds it to the top of the container.


2 Answers

std::vector::insert copies or moves the elements into the container by calling copy constructor or move constructor.
while,
In std::vector::emplace elements are constructed in-place, i.e. no copy or move operations are performed.

The later was introduced since C++11 and its usage is desirable if copying your class is a non trivial operation.

like image 174
Alok Save Avatar answered Sep 29 '22 19:09

Alok Save


The primary difference is that insert takes an object whose type is the same as the container type and copies that argument into the container. emplace takes a more or less arbitrary argument list and constructs an object in the container from those arguments.

like image 25
Pete Becker Avatar answered Sep 29 '22 19:09

Pete Becker