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 task

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

Challenge 2

The input is name kills pairs from several rounds. Add up each player's kills with a std::map and print name total lines in alphabetical order. Input ropz 3 rain 1 ropz 4 prints rain 1 and ropz 7.

Challenge 3

Count the words in the input, then print word count lines sorted by count, most first, with ties in alphabetical order. A map sorts by key only, so copy its entries into a vector and sort that.

Next: Look up without inserting