Step 1 of 6
std::map
A vector finds things by position: element 0, element 1, and so on. Often you want to find things by a name instead: the score for "ropz", the price of "awp", the phone number for "Ada". That's what a map is for. std::map<Key, Value> stores key/value pairs, keeps them sorted by key, and never holds the same key twice.
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> stock;
stock["apple"] = 5;
stock["pear"] = 2;
stock["apple"] += 3; // the key exists, so this updates it
stock["kiwi"]++; // the key is new, so it starts at 0, then becomes 1
std::cout << stock.size() << " kinds\n";
for (const auto& [fruit, n] : stock) {
std::cout << fruit << ": " << n << "\n";
}
}
3 kinds
apple: 8
kiwi: 1
pear: 2
How it works
m[key]gives you a reference to the value forkey. If the key isn't there yet,[]first inserts it with a default value:0for numbers,""for strings. That's whystock["kiwi"]++works on a brand new key.- Looping over a map visits the entries in key order (alphabetical for strings, ascending for numbers), no matter what order you inserted them in.
- Each entry is a
std::pair<const Key, Value>.const auto& [fruit, n]is a structured binding: it unpacks the pair into two named variables. Without it you'd writeentry.firstandentry.second. - A map is a balanced binary search tree inside, so insert and lookup take O(log n) steps.
The counting pattern
"How many times does each thing appear?" is one of the most common jobs in programming, and a map makes it one line: count[thing]++. Missing keys start at 0 automatically.
Common mistakes
- Writing
for (auto [k, v] : m)copies every entry. Useconst auto&to read without copying. - Forgetting that a map keeps only one value per key. Assigning to an existing key replaces the old value.
Your turn: count how many times each word appears in the input and print word count lines in alphabetical order.