bhylu.com

Advertisements

C++ Sets

Use a set for unique zone names and handle a duplicate insertion explicitly.

How it works

std::set stores unique keys ordered by a comparison relation. Its normal lookup and insertion guarantees are logarithmic in the number of elements. It is useful when iteration order is part of the requirement. The comparator must define a strict weak ordering; a comparator whose result changes according to unrelated mutable state can break the container contract. Keys cannot be modified in place through an iterator because that could violate ordering.

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 sets.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 · sets.cpp

#include <iostream>
#include <set>
#include <string>

int main() {
    std::set<std::string> zones{"West", "East"};
    auto [position, inserted] = zones.insert("West");
    std::cout << "Duplicate added: " << inserted << "; existing: " << *position << '\n';
    for (const auto& zone : zones) { std::cout << zone << '\n'; }
}

Expected result

Duplicate added: 0; existing: West
East
West

The insertion returns the position of the already-present key and a false added flag. Iteration is ordered by the default string comparison, not insertion order. multiset permits equivalent keys when duplicates are meaningful. If only membership matters, an unordered_set can offer a different average-cost tradeoff without promising sorted iteration.

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.