C++ Snippet

std::unordered_map Quick Reference

Difficulty: Easy

`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.

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

871 views

5

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.