C++ · Module 13 · Lesson 31 min read

Ordered Containers: set & map

std::set<T> — unique, sorted values

c
std::set<std::string> tags = { "food", "rent", "food" };   // {"food", "rent"}
tags.insert("travel");
tags.count("rent");        // 1 or 0
tags.contains("rent");     // C++20 ✅
tags.erase("food");

Iterates in sorted order. Implemented as a balanced binary search tree (red-black tree).

std::map<Key, Value> — sorted key → value pairs

c
std::map<std::string, double> budget;
budget["Food"] = 5000;           // insert or update
budget["Rent"] += 15000;         // missing key → value-initialized (0) first!
budget.at("Food");               // throws std::out_of_range if missing
budget.contains("Gym");          // C++20

Elements are std::pair<const Key, Value> → use .first/.second or structured bindings.

⚠️ The operator[] trap

m[key] inserts a default value if the key doesn't exist — even if you only wanted to read. Use find, contains or at to look up without inserting. operator[] also doesn't work on a const map.

Finding

c
if (auto it = budget.find("Rent"); it != budget.end()) {
    std::cout << it->second;
}

Inserting without overwriting

m.insert({k, v}) / m.try_emplace(k, v) do nothing if the key exists (they return whether it inserted). m.insert_or_assign(k, v) always sets.

Range queries

lower_bound(k) (first ≥ k), upper_bound(k) (first > k) — great for dates, prices, score bands.

Multi-versions

std::multiset, std::multimap allow duplicate keys (e.g. several expenses on the same date). Use equal_range(k) to get all of them.

Custom ordering

std::set<int, std::greater<int>> sorts descending. For your own types, define operator< / <=> or pass a comparator.

Complexity

insert, erase, find: O(log n); iteration in sorted order: O(n).

Example

C++
#include <iostream>
#include <map>
#include <set>
#include <string>

int main() {
    std::set<std::string> tags = { "food", "rent", "food", "travel" };
    tags.insert("bills");
    std::cout << "tags (" << tags.size() << "):";
    for (const auto& t : tags) std::cout << ' ' << t;
    std::cout << std::boolalpha << "\ncontains rent? " << tags.contains("rent") << '\n';

    std::map<std::string, double> spent;
    spent["Food"] += 450;                      // missing key starts at 0.0
    spent["Rent"] = 15000;
    spent["Food"] += 1200;
    spent.insert({ "Travel", 800 });
    auto [pos, inserted] = spent.insert({ "Rent", 1 });      // key exists: nothing changes
    std::cout << "insert Rent again inserted? " << inserted << " (still " << pos->second << ")\n";

    for (const auto& [category, amount] : spent)              // sorted by key
        std::cout << "  " << category << ": " << amount << '\n';

    if (auto it = spent.find("Travel"); it != spent.end()) std::cout << "Travel found: " << it->second << '\n';
    std::cout << "size before reading Gym with []: " << spent.size();
    double gym = spent["Gym"];                                  // ⚠️ inserts Gym = 0
    std::cout << ", after: " << spent.size() << " (gym = " << gym << ")\n";
    try {
        std::cout << spent.at("Movies");
    } catch (const std::out_of_range&) {
        std::cout << "at(\"Movies\") threw out_of_range\n";
    }

    // grade bands with upper_bound
    std::map<int, char> bands = { { 0, 'F' }, { 40, 'C' }, { 60, 'B' }, { 80, 'A' } };
    for (int score : { 35, 60, 79, 95 }) {
        auto it = std::prev(bands.upper_bound(score));        // last band whose start <= score
        std::cout << score << " -> " << it->second << "  ";
    }
    std::cout << '\n';

    std::multimap<std::string, int> by_date = { { "11-01", 300 }, { "11-02", 450 }, { "11-01", 15000 } };
    auto [first, last] = by_date.equal_range("11-01");
    int day_total = 0;
    for (auto it = first; it != last; ++it) day_total += it->second;
    std::cout << "spent on 11-01: " << day_total << " in " << by_date.count("11-01") << " entries\n";

    std::set<int, std::greater<int>> top = { 50, 90, 70 };
    std::cout << "descending set:";
    for (int x : top) std::cout << ' ' << x;
    std::cout << '\n';
    return 0;
}

/* Output:
tags (4): bills food rent travel
contains rent? true
insert Rent again inserted? false (still 15000)
  Food: 1650
  Rent: 15000
  Travel: 800
Travel found: 800
size before reading Gym with []: 3, after: 4 (gym = 0)
at("Movies") threw out_of_range
35 -> F  60 -> B  79 -> B  95 -> A
spent on 11-01: 15300 in 2 entries
descending set: 90 70 50
*/