Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::vector emplace vs insert [duplicate]

Tags:

c++

stl

vector

I was wondering what are the differences between the two. I notice that emplace is c++11 addition. So why the addition ?

like image 707
Aditya Sihag Avatar asked Feb 09 '13 12:02

Aditya Sihag


People also ask

Is emplace better than insert?

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 insert and emplace in C++?

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.

What is the use of emplace in C++?

C++ Vector Library - emplace() Function The C++ function std::vector::emplace() extends container by inserting new element at position. Reallocation happens if there is need of more space. This method increases container size by one.

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

Emplace takes the arguments necessary to construct an object in place, whereas insert takes (a reference to) an object.

struct Foo {   Foo(int n, double x); };  std::vector<Foo> v; v.emplace(someIterator, 42, 3.1416); v.insert(someIterator, Foo(42, 3.1416)); 
like image 105
juanchopanza Avatar answered Oct 02 '22 14:10

juanchopanza


insert copies objects into the vector.

emplace construct them inside of the vector.

like image 42
hate-engine Avatar answered Oct 02 '22 14:10

hate-engine