What is the difference between insert and emplace for a vector in C ++

Besides single insert using emplace and multiple insert using insert into vector, is there any other difference in their implementation?

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

+2
source share
2 answers

std::vector::insert copies or moves elements to the container by calling the copy constructor or moving the constructor.
while,
In std::vector::emplace elements are built in place , that is, copy or move operations are not performed.

It was later introduced with C ++ 11, and its use is desirable if copying for your class is a nontrivial operation.

+6
source

The main difference is that insert accepts an object whose type matches the type of the container and copies this argument to the container. emplace accepts a more or less arbitrary list of arguments and constructs an object in the container from these arguments.

0
source

Source: https://habr.com/ru/post/972524/


All Articles