Skip to content
Guest
Learn C++ · Course Syllabus Show lessons
The Standard Library (STL) · 8 min read · Intermediate

unordered_map & Structured Bindings

Perform O(1) hash lookups with std::unordered_map and unpack key-value pairs cleanly with C++17 structured bindings.

What you'll learn

  • Count frequencies and store key-value pairs in std::unordered_map
  • Iterate cleanly with for (const auto& [key, val] : map)
  • Check membership safely with .contains() (C++20) or .find()

std::unordered_map<K, V> provides average $O(1)$ hash-table lookups. With C++17 structured bindings (const auto& [key, value]), iterating over maps is concise and readable.

Fill-in-the-Blank Exercise

Structured Binding Loop

Unpack each key and count while iterating over a map.

for (const & [, count] : counts) {
  std::cout << word << ": " << count << "\n";
}

Live Code Lab

C++maps_demo.cpp
Expected OutputClick “Run Live” to compile with GCC 13 (C++20)
cpp count: 2
has rust? no

Check Your Understanding

Score: 0 / 1

1. What happens in C++ if you read map["missing"] on an std::unordered_map<std::string, int>?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind