bhylu.com

Advertisements

C++ Maps

Look up a zone without accidentally inserting it and update a known count deliberately.

How it works

std::map stores ordered unique keys associated with values. find and contains observe membership; operator[] can insert a missing key with a value-initialized mapped value. That difference matters when a lookup should not mutate a manifest. Use insert_or_assign for an explicit update-or-create operation, and at when a missing key is an error under your contract. Ordered iteration can make reports reproducible without sorting a separate key list.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror maps.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · maps.cpp

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> parcels{{"West", 4}, {"East", 2}};
    auto missing = parcels.find("North");
    std::cout << "North absent: " << (missing == parcels.end()) << '\n';
    parcels.insert_or_assign("West", 6);
    for (const auto& [zone, count] : parcels) { std::cout << zone << ": " << count << '\n'; }
}

Expected result

North absent: 1
East: 2
West: 6

find leaves the two-entry map unchanged. Structured bindings give readable names to each key and mapped count while const references avoid copying. A map is not a database transaction mechanism; it provides in-memory container semantics only. Real persisted updates require an application-level validation and commit policy.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.