I was wondering what are the differences between the two. I notice that emplace is c++11 addition. So why the addition ?
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.
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.
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.
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.
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));
insert
copies objects into the vector.
emplace
construct them inside of the vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With