Lesson 13 of 24

map and unordered_map

10 min 35 XP

A map stores a value per key with keys kept sorted (O(log n)). unordered_map has no order but averages O(1). Counting is as simple as m[key]++.

Example: edit me and press Run

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.

for (auto& [key, value] : m) uses C++17 structured bindings. Reading m[key] inserts the key with 0 if it's missing; use count() or find() just to check.

Challenge

+35 XP

Read n and then n words. Print how many times each word appears, in alphabetical order. Input: 6 apple mango apple kiwi mango apple Output: apple 3 kiwi 1 mango 2

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.