C++ std::unordered_map insert() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::unordered_map

Definition

In C++, std::unordered_map::insert() adds a new pair to a std::unordered_map. The pair is placed into a hash bucket. Keys stay unique, but not sorted.

If the key is already in the unordered_map, insert() does nothing and the old value stays. The m[key] = value form is different: it creates the key if needed and always overwrites the value. Include <unordered_map> to use it.

This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.

Syntax

Pass a pair, a braced pair, an initializer list, or a range of pairs.

C++
auto r = m.insert({"one", 1});        // one pair
m.insert(std::make_pair("two", 2));   // pair made with make_pair
m.insert({{"c", 3}, {"d", 4}});       // initializer list
m.insert(other.begin(), other.end()); // a range of pairs
CallWhat it does
m.insert(pair)Adds the pair if its key is new. Returns std::pair<iterator, bool>.
m.insert(hint, pair)Same, but uses hint as a starting position to be faster. Returns an iterator.
m.insert(first, last)Inserts every pair from the range. Pairs with keys that already exist are skipped.
m.insert({p1, p2, ...})Inserts all pairs in the initializer list, skipping duplicate keys.
m.insert(std::move(node))Inserts a node handle from extract() (C++17).

Since C++17 you also have insert_or_assign() to update existing values and try_emplace() to avoid wasted work. emplace() builds the pair in place.

Library declarations
C++
std::pair<iterator, bool> insert(const value_type& value);
std::pair<iterator, bool> insert(value_type&& value);
iterator insert(const_iterator hint, const value_type& value);
template<class InputIt> void insert(InputIt first, InputIt last);
void insert(std::initializer_list<value_type> ilist);
insert_return_type insert(node_type&& nh);   // C++17

Parameters

ParameterDescription
valueThe pair to add, of type std::pair<const Key, T>. A braced pair such as {"one", 1} works.
hintAn iterator near where the pair will go. It only helps speed; it does not change the result.
first, lastA range of pairs to insert.
ilistA braced list of pairs.
nhA node handle returned by extract().

Return Value

Return ValueDescription
pair<iterator, bool>first points to the pair with that key. second is true if a new pair was added, and false if the key already existed.
iteratorFor the hint form: an iterator to the pair with that key, new or old.
voidFor the range and initializer list forms.

C++ Examples

Example 1 — insert() Reports If It Added the Pair

Insert the same key twice and read the bool that insert() returns.

C++
#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> m;
    std::cout << std::boolalpha;

    auto r1 = m.insert({"one", 1});
    auto r2 = m.insert({"one", 100});

    std::cout << "first insert added: " << r1.second << '\n';
    std::cout << "second insert added: " << r2.second << '\n';
    std::cout << "value is still: " << r2.first->second << '\n';
    return 0;
}

How It Works

  1. insert({"one", 1}) finds no key "one", so it adds the pair. The returned second is true.
  2. The second insert uses the same key. The unordered_map keeps keys unique, so it adds nothing and second is false.
  3. r2.first is an iterator to the existing pair, and its value is still 1. The 100 was thrown away.

Example 2 — insert() with a List and a Range

Add pairs with an initializer list and then with a range from another map.

C++
#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> m = {{"b", 2}};
    std::unordered_map<std::string, int> other = {{"d", 4}, {"a", 50}};

    m.insert({{"c", 3}, {"a", 1}, {"b", 99}});
    m.insert(other.begin(), other.end());

    std::cout << "a=" << m.at("a") << " b=" << m.at("b")
              << " c=" << m.at("c") << " d=" << m.at("d")
              << " (size " << m.size() << ")\n";
    return 0;
}

How It Works

  1. The list form adds c and a. The pair {"b", 99} is skipped because "b" already exists, so b stays 2.
  2. The range form copies pairs from other. d is new and added. {"a", 50} is skipped because a is already 1.
  3. Values are printed with at() so the demo does not depend on iteration order.

Example 3 — insert() Compared with operator[]

See that insert() keeps old values, that [] overwrites them, and that reading with [] can add a key.

C++
#include <iostream>
#include <unordered_map>
#include <string>

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

    m.insert({"x", 1});
    m.insert({"x", 2});      // ignored
    m["y"] = 1;
    m["y"] = 2;              // overwrites

    int q = m["q"];          // only reading, but q is added with 0
    std::cout << "q = " << q << ", size = " << m.size() << '\n';
    std::cout << "q=" << m.at("q") << " x=" << m.at("x") << " y=" << m.at("y") << '\n';
    return 0;
}

How It Works

  1. insert({"x", 2}) is ignored because "x" exists, so x keeps the value 1.
  2. m["y"] = 2 overwrites the earlier 1, because the bracket operator assigns every time.
  3. m["q"] does not find "q", so it inserts it with the default 0 even though you only read it. That is why the size is 3 and q=0 appears.

Frequently Asked Questions

The single-pair form returns std::pair<iterator, bool>. The iterator points at the pair with that key, and the bool is true only if a new pair was added.
Nothing. The unordered_map is not changed and the old value stays. The returned bool is false.
insert() adds only new keys and keeps old values. m[key] = value adds the key if needed and always sets the value. Also, m[key] on a missing key inserts a default value even when you only read it.
Use m[key] = value, m.at(key) = value, or insert_or_assign() in C++17. insert() will not update it.
No. unordered_map does not sort keys. Iteration order is unspecified.

Next: insert_or_assign()

Keep going through the std::unordered_map functions. Insert a new key, or update the value if the key exists (C++17).

insert_or_assign() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful