Here is a piece of code in my daily work. I just want to ask you if there is any difference between the two cases, especially in terms of performance.
std::vector< std::pair<std::string, std::string> > aVec;
// case 1
aVec.emplace_back("hello", "bonjour");
// case 2
aVec.emplace_back(std::pair("hello", "bonjour"));
Following question:
What about a std::list for these two cases?
C++ Vector Library - emplace_back() Function The C++ function std::vector::emplace_back() inserts new element at the end of vector. Reallocation happens if there is need of more space. This method increases container size by one.
With the simple benchmark here, we notice that emplace_back is 7.62% faster than push_back when we insert 1,000,000 object (MyClass) into an vector.
Specific use case for emplace_back : If you need to create a temporary object which will then be pushed into a container, use emplace_back instead of push_back . It will create the object in-place within the container.
So you can emplace_back does use the desired constructor to create the element and call copy constructor when it need to grow the storage. You can call reserve with enough capacity upfront to avoid the need to call copy constructor.
emplace_back will construct the element in-place, the argument passed in will be perfect-forwarded to the constructor for the element.
For the 1st case, conceptually only one step is needed, i.e. the appropriate constructor of std::pair
will be invoked to construct the element directly in vector
.
For the 2nd case, three steps is needed; (1) the appropriate constructor will be invoked to construct a temporary std::pair
, (2) the element will be move constructed in vector
in-place from the temporary std::pair
, (3) the temporary std::pair
is destroyed.
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