emplace() vs insert() when using std::unordered_map

When should I use emplace() instead of insert() for std::unordered_map?

The emplace() method constructs the key-value pair directly within the map, while insert() requires creating the pair outside the map and then moving or copying it in.

Using emplace() can be more efficient, especially when the key or value type is expensive to copy or move. Here's an example:

#include <iostream>
#include <string>
#include <unordered_map>

struct User {
  std::string Name;
  // Other data members...

  User(const std::string& name) : Name{name} {  
    std::cout << "User constructed\n";          
  }                                             
};

int main() {
  std::unordered_map<std::string, User> users;

  users.emplace("john", "John");  

  auto [it, success] = users.insert(
    {"alice", User{"Alice"}}
  );  
}
User constructed
User constructed

When using emplace(), the User object is constructed directly within the map using the provided arguments. With insert(), we first construct a User object outside the map and then insert it, resulting in an extra construction.

However, if you already have an existing key-value pair object, using insert() can be more convenient and readable.

In summary, prefer emplace() when you have the individual key and value components available, especially for complex types. Use insert() when you already have a key-value pair object ready to be inserted.

Hash Maps using std::unordered_map

Creating hash maps using the standard library's std::unordered_map container

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

std::unordered_map Performance Considerations
What factors affect the performance of std::unordered_map operations?
Requirements for Custom Key Types in std::unordered_map
What are the requirements for using a custom type as the key in std::unordered_map?
std::unordered_map vs std::map - When to Use Each
When should I use std::unordered_map instead of std::map?
Handling Hash Collisions in std::unordered_map
How does std::unordered_map handle hash collisions?
Error Handling in std::unordered_map
How can I handle errors and exceptions when using std::unordered_map?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant