C++ std::unordered_map

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

Definition and Usage

In C++, std::unordered_map<Key, T> is a container that stores key and value pairs in a hash table. You look up a value by its key. The keys are unique and are not kept sorted. Iteration order is unspecified.

Finding, inserting, and erasing a key are usually average constant time. Read a value with at() or find(), add pairs with insert() or emplace(), and call reserve() before many inserts. Include <unordered_map> to use it.

This page teaches what a std::unordered_map is. The Unordered Map Functions index lists every function guide in this series.

Why choose an unordered_map?

Choose an unordered_map when you need fast key lookup and do not need sorted keys, for example names to ages, words to counts, or ids to records. If you need sorted output or lower_bound-style searches, use std::map. If you only need a list of values by position, use a std::vector.

C++ Syntax

Common ways to create and use a std::unordered_map:

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

std::unordered_map<std::string, int> a;                         // empty
std::unordered_map<std::string, int> b = {{"b", 2}, {"a", 1}};  // order unspecified

b.reserve(10);                   // prepare buckets
b["c"] = 3;                      // add or update with []
b.insert({"d", 4});              // add only if the key is new
b.emplace("e", 5);               // build the pair in place
int x = b.at("a");               // throws if missing
auto it = b.find("c");           // iterator, or b.end()
bool has = b.contains("z");      // false (C++20)
b.erase("d");                    // remove by key
std::size_t n = b.size();        // number of pairs

std::unordered_map vs std::map vs std::vector

Here is a quick comparison of three containers that beginners often mix up:

Featurestd::unordered_mapstd::mapstd::vector
StoresKey and value pairsKey and value pairsValues only
Order of elementsUnspecified (hash buckets)Sorted by keyThe order you added them
Find by keyUsually constantLogarithmicLinear (search by value)
Duplicate keysNot allowedNot allowedNot applicable
Ordered search (lower_bound())NoYesOnly if you sort it
Key type needsA hash and operator==operator< or a comparatorNot applicable
Header<unordered_map><map><vector>

When to Use find(), at(), [] or contains()

Several members read or test a key, but they react differently when the key is missing:

Way to readIf the key is missingUse it when you…
find()Returns end(). The map is not changed.Are not sure the key exists, and want to handle both cases
at()Throws std::out_of_rangeExpect the key to exist and want a loud error if it does not
m[key]Adds the key with a default value (0, empty string, ...)Want to create or update on purpose, such as ++count[word]. It cannot be used on a const map.
contains() / count()Returns false or 0Only need to know whether a key exists
reserve()Does not look up a keyKnow about how many keys you will insert and want fewer rehashes

C++ Examples

Three short programs that show how std::unordered_map works.

Example 1 — Add Pairs and Look Them Up

A first program that adds pairs three ways and reads them by key. Iteration order is unspecified, so this demo prints by looking up each name.

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

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

    age["Raj"] = 25;
    age.insert({"Mia", 21});
    age.emplace("Zoe", 30);

    std::cout << "Raj: " << age.at("Raj") << '\n';
    std::cout << "Mia: " << age.at("Mia") << '\n';
    std::cout << "Zoe: " << age.at("Zoe") << '\n';
    std::cout << "size: " << age.size() << '\n';
    return 0;
}

How It Works

  1. std::unordered_map<std::string, int> starts empty. The key is a name and the value is an age.
  2. age["Raj"] = 25, insert({"Mia", 21}), and emplace("Zoe", 30) each add one pair into a hash bucket.
  3. The program prints each value with at() so the output order does not depend on iteration order. size() counts the three pairs.

Example 2 — Read a Missing Key with find(), at() and []

The three ways to read an unordered_map act differently when the key is missing. This is the most important thing to learn.

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

int main() {
    std::unordered_map<std::string, int> stock = {{"apple", 5}};

    auto it = stock.find("kiwi");
    std::cout << (it == stock.end() ? "find: not found" : "find: found") << '\n';

    try {
        stock.at("kiwi");
    } catch (const std::out_of_range&) {
        std::cout << "at: threw out_of_range\n";
    }

    std::cout << "size before []: " << stock.size() << '\n';
    int n = stock["kiwi"];
    std::cout << "[] gave " << n << ", size after: " << stock.size() << '\n';
    return 0;
}

How It Works

  1. find("kiwi") returns end() because there is no such key. It never throws and it never changes the map.
  2. at("kiwi") throws std::out_of_range, so the catch block runs. The map is still unchanged, with 1 pair.
  3. stock["kiwi"] does not fail. It adds the key with the default value 0 and returns it. Even a read made the map bigger, and the size is now 2.

Example 3 — Count Words Faster with reserve()

An unordered_map is great for counting. Call reserve() first when you know about how many different keys you will see.

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

int main() {
    std::vector<std::string> words = {"pear", "apple", "fig", "pear", "kiwi", "apple", "pear"};
    std::unordered_map<std::string, int> freq;
    freq.reserve(words.size());

    for (const std::string& w : words) {
        ++freq[w];
    }

    std::cout << "apple: " << freq.at("apple") << '\n';
    std::cout << "pear: " << freq.at("pear") << '\n';
    std::cout << "distinct: " << freq.size() << '\n';
    return 0;
}

How It Works

  1. reserve(words.size()) prepares buckets so the counting loop does less rehashing.
  2. ++freq[w] inserts a new word with 0 then adds one. Repeated words only raise the count.
  3. The program prints counts with at() and shows four distinct keys. Unlike std::map, there is no sorted walk here.

Next: C++ std::unordered_map Functions Index

After you know what a std::unordered_map is, open the function index for a full tutorial on each member function.

Start withWhy
insert()Add a new key and value pair
find()Search for a key without adding it
reserve()Prepare buckets before many inserts
erase()Remove a pair by key or by iterator

Full list: C++ std::unordered_map Functions index (/cpp/unordered-map/function).

Frequently Asked Questions

std::unordered_map<Key, T> is a hash table from <unordered_map>. It stores key and value pairs, keeps keys unique, and finds a key in average constant time. Iteration order is unspecified.
unordered_map uses hashing, is usually faster to find a key, and does not sort keys. map keeps keys sorted and finds in logarithmic time. Choose map when you need sorted output or lower_bound-style range searches.
find() returns an iterator and gives end() for a missing key. at() returns the value but throws std::out_of_range for a missing key. m[key] never fails, but it adds a missing key with a default value, which changes the map.
Call reserve(n) before you insert about n keys. It grows the bucket table once and avoids repeated rehashes during a big loop.
Open the C++ std::unordered_map Functions index. It lists every member function in this series, from insert() and find() to reserve(), rehash(), and hash_function().

Browse every unordered_map function

Open the functions index for categorized guides with examples and FAQs.

Function Index →

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.

8 people found this page helpful