bhylu.com

Advertisements

C++ Unordered Containers

Use unordered_map for keyed access and print known keys rather than relying on bucket iteration order.

How it works

std::unordered_map organizes keys using a hash function and equality predicate. Its average lookup is constant-time under suitable distribution assumptions, but worst-case work can be linear. Equal keys must produce equal hashes. Rehashing can invalidate iterators, so do not retain an iterator across a growth operation without checking the contract. The container has no sorted iteration promise; reproducible reports should explicitly select or sort their output keys.

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 hash-containers.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 · hash-containers.cpp

#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> counts{{"Quay", 4}, {"Gate", 2}};
    counts.reserve(12);
    counts.insert_or_assign("Quay", 7);
    std::cout << "Quay: " << counts.at("Quay") << '\n';
    std::cout << "Gate: " << counts.at("Gate") << '\n';
}

Expected result

Quay: 7
Gate: 2

The fixture looks up known keys in an explicitly chosen display order. reserve prepares for a desired element count under the current load-factor policy; it does not create those entries. For adversarial keys or strict worst-case requirements, assess the hashing policy and possible alternative structures instead of assuming average complexity is a guarantee.

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.