Hash Maps using std::unordered_map

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

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved