Benefits of using emplace
over insert
What are the advantages of using emplace_front()
or emplace_back()
instead of push_front()
or push_back()
?
The emplace_front()
and emplace_back()
methods of std::deque
construct elements in-place at the front or back of the deque, while push_front()
and push_back()
copy or move an existing object into the deque.
Using emplace_front()
or emplace_back()
can be more efficient because:
- It avoids creating a temporary object. With
push_front()
orpush_back()
, you often need to create an object before adding it to the deque.emplace_front()
andemplace_back()
construct the object directly in the deque's memory. - It avoids the copy or move operation. After creating the temporary object,
push_front()
orpush_back()
need to copy or move it into the deque.emplace_front()
andemplace_back()
avoid this step.
Here's an example:
#include <deque>
#include <string>
#include <iostream>
struct User {
std::string name;
int id;
User(std::string name, int id)
: name(name), id(id) {
std::cout << "Constructing User "
<< name << "\n";
}
User(const User& other)
: name(other.name), id(other.id) {
std::cout << "Copying User "
<< name << "\n";
}
};
int main() {
std::deque<User> users;
users.emplace_back("Alice", 1);
User bob("Bob", 2);
users.push_back(bob);
}
Constructing User Alice
Constructing User Bob
Copying User Bob
When using emplace_back()
, the User
object is constructed directly in the deque. When using push_back()
, the User
object is first constructed, then copied into the deque.
However, the performance difference is only significant for types that are expensive to copy or move. For simple types like int
or double
, there's likely no noticeable difference.
Double-Ended Queues using std::deque
A guide to double-ended queues - a structure that behaves like a vector, specialised for manipulating objects at the edges of the collection