Lesson 5 of 12

One key, one record

Use maps without confusing lookup, insertion, and replacement.

Two columns with a unique key

std::map<Key, Value>, from <map>, stores one mapped value per unique key and traverses entries by key. Equal mapped scores do not merge records. A name-to-score map orders names, not scores. There is no standard std::ordered_map spelling.

Decide what a repeated key should mean. m[key] = value keeps the latest value; m[key] += amount accumulates; insert({key, value}) keeps the first. insert_or_assign explicitly replaces, while try_emplace preserves an existing mapped value. Argument expressions are still evaluated before the call.

A read-looking expression can insert

m[key] returns the mapped value by reference. If absent, the key is first inserted with a default value: zero for an integer, empty for a string or vector. This is useful for counting and grouping; it is often wrong for read-only queries.

find returns end() when absent. contains returns existence. at returns the value but throws std::out_of_range for an absent key. count is 0 or 1 for map entries; if m[7] stores 12, then count(7) is 1 and at(7) is 12. Never use a mapped zero as proof of absence.

C++23
// Complete C++23 program. Input: n q, n name-score pairs, q names.
#include <iostream>
#include <map>
#include <string>
int main() {
    int n, q;
    std::cin >> n >> q;
    std::map<std::string, int> scores;
    for (int i = 0; i < n; ++i) {
        std::string name;
        int score;
        std::cin >> name >> score;
        scores[name] = score;
    }
    while (q--) {
        std::string name;
        std::cin >> name;
        auto it = scores.find(name);
        if (it == scores.end()) std::cout << "MISSING\n";
        else std::cout << it->second << '\n';
    }
}

Modify values, preserve keys

A map iterator exposes a key–value pair: first is a const key and second is the mapped value. for (auto& entry : scores) changes actual records; for (auto entry : scores) changes only copies. Use const auto& for read-only traversal to avoid copying key text or large mapped values.

A read-only helper should take const std::map<...>& to avoid copying the whole table. It cannot use operator[] through that const reference. Standard map iterator erasure follows the same guarded return-next pattern as set erasure.

Word frequency map

Split on whitespace. Keys are case-sensitive; punctuation stays attached. Displayed in sorted key order like std::map<string, int>.

code3
learn2
solve1

6 words · 3 distinct keys

Guided simulation · Change the inputs to test your understanding.

Pause & predict

An empty map<string,int> m executes cout << m["nour"]. What has happened afterward?

Choose an answer
Try it yourself

Turn the idea into code

The updates for one product are 10, 4, 7. Give the result for keeping the first price, latest price, and total amount, and identify an operation for each.

Give me a hint

The declaration can stay the same; the repeated-key policy is expressed by the update.

Show the explained solution

First: 10 using insert or try_emplace. Latest: 7 using assignment or insert_or_assign. Total: 21 using +=. Query with find when absence is possible, so inspecting an unknown product does not add a record.

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.