← C++ from Scratch
Lesson 59 of 62 · 10 XP
map
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
std::map<Key, Value> is a dictionary: find a value quickly by its key. The keys are stored in order.
#include <map>
std::map<std::string, int> stock;
stock["potion"] = 3; // add or change
stock["potion"] += 2; // 5
stock["arrow"]++; // there was no such key — it's created with the value 0 and becomes 1
stock.count("bow"); // 0 — there's no such key (accessing it with [] would create it!)
for (const auto &[name, qty] : stock) // go through the pairs in key order
std::cout << name << ' ' << qty << '\n';
std::unordered_map has no order and is faster on average. A common task is counting frequencies: freq[word]++.
Task. Read text until the end of the input. Count how many times each word appears (convert it to lower case,
and drop the characters .,!? at the edges of a word). Print the 3 most frequent words in the format word count
(on a tie — in alphabetical order).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.