Code Snippets
/

std::unordered_map Quick Reference

std::unordered_map Quick Reference

`std::unordered_map` is the default hash table in C++: average O(1) insert, lookup, and erase. This snippet covers insertion, the right way to test for membership without inserting a default, iteration, and structured bindings (C++17) for clean key/value loops. Use it whenever you need a dictionary; reach for `std::map` only when you need keys in sorted order.

C++
Easy
3 snippets
cpp-stl
cpp-containers
hash-map

872 views

5

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

int main() {
    std::unordered_map<std::string, int> ages;
    ages["ada"] = 36;
    ages["linus"] = 54;
    ages.insert({"margaret", 88});

    std::cout << "ada=" << ages["ada"] << " size=" << ages.size() << "\n";
    return 0;
}

operator[] inserts a default-constructed value (here 0) if the key is missing, then returns a reference to it. That makes assignment as simple as m[key] = value, but it also means cout << m["missing"] will INSERT an empty entry as a side effect. For pure look-ups always use find or contains (next accordion) to avoid that surprise. insert({k, v}) only adds when the key is new and returns a pair<iterator, bool> you can inspect to see whether the insert happened.