Skip to content
AgileLogics
4 min read

Maps & Associative Containers

Prerequisites: Vectors & sequence containers

#include <map>
#include <unordered_map>

std::map<std::string, int> ages;       // kept sorted by key
std::unordered_map<std::string, int> fast; // hash-based, unordered

ages["Ada"] = 36;
ages["Grace"] = 85;

if (ages.count("Ada")) {
    std::cout << ages["Ada"] << std::endl; // 36
}

for (const auto &[name, age] : ages) { // structured bindings (C++17)
    std::cout << name << " is " << age << std::endl;
}

std::set/std::unordered_set are the associative equivalent of a map with no attached value — just "is this present," ordered or hash-based respectively.

Common mistakes

  • Using ages["key"] to check whether a key exists — this silently inserts a default-valued entry for a missing key. Use .count("key") or .find("key") != ages.end() to check without inserting.