Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use always emplace to replace insert for single element insertion?

Tags:

c++

c++11

I was wondering if it is OK to always use emplace to replace insert when inserting a single element into a STL container, like set, unordered_set?

From the signature, emplace is simpler and do not involve overloads. Is there any issue with stop using insert and use emplace all the time?

Note: there are SO questions asking about the difference between emplace and insert/push_back etc. (e.g. here, here, and here) I understand the difference, and it seems to me that emplace is better in every way. I just want to confirm if it's OK to deprecate insert.

like image 955
thor Avatar asked Jul 20 '14 02:07

thor


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?

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.

Is Emplace_back faster than Push_back?

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.


1 Answers

There are some examples here that can be adapted to emplace and insert, showing when the behaviour may differ.

These examples may seem a bit artificial, so I'll give one that will hopefully appear less so:

#include <set>

template <typename T>
T id(T x) { return x; }

int main() {
    std::set<int(*)(int)> s;
    s.insert(id);       // OK
    s.emplace(id);      // error
    s.emplace(id<int>); // OK
}

insert can deduce the template parameter of id because it knows what type it wants. For emplace you get an error unless you explicitly specify.

like image 97
Brian Bi Avatar answered Nov 06 '22 23:11

Brian Bi