C/C++ Arena

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

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

Your turn: count how many times each word appears in the input and print word count lines in alphabetical order.

Next: Look up without inserting