← C++ Index

🗺️ <map> — std::map & std::unordered_map — Associative Containers

std::map is a sorted key-value store (red-black tree, O(log n)). std::unordered_map is a hash table (O(1) average). Include <map> and <unordered_map> respectively.

Include: #include <map> | Namespace: std | Compile: g++ -Wall -std=c++17 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::map<K,V>class templateSorted associative container
std::unordered_map<K,V>class templateHash-based associative container
m[key]V &Access/insert by key
m.at(key)V &Access by key; throws if absent
m.insert({k,v})pair<it,bool>Insert key-value pair
m.emplace(k,v)pair<it,bool>Construct pair in-place
m.erase(key)size_tRemove element by key
m.find(key)iteratorIterator to key or m.end()
m.count(key)size_tCount of key (0 or 1 for map)
m.contains(key)boolTrue if key exists (C++20)
m.size()size_tNumber of key-value pairs
m.empty()boolTrue if map has no elements
m.clear()voidRemove all elements
m.lower_bound(key)iteratorFirst element >= key (map only)
m.upper_bound(key)iteratorFirst element > key (map only)

💡 Example Program

Copy, save as demo.cpp, and compile with the command at the bottom.

#include <iostream>
#include <map>
#include <unordered_map>
#include <string>
using namespace std;

int main() {
    map<string, int> scores;
    scores["Alice"] = 95; scores["Bob"] = 87;
    scores["Carol"] = 92; scores["Dave"] = 78;

    cout << "Sorted scores:\n";
    for (auto &[name, score] : scores)
        cout << "  " << name << " : " << score << "\n";

    scores.erase("Dave");
    cout << "After erasing Dave, size=" << scores.size() << "\n";

    unordered_map<string, int> word_count;
    string text[] = {"apple","banana","apple","cherry","banana","apple"};
    for (auto &w : text) word_count[w]++;

    cout << "\nWord counts:\n";
    for (auto &[word, cnt] : word_count)
        cout << "  " << word << " : " << cnt << "\n";
    return 0;
}
// Compile: g++ -Wall -std=c++17 -o map_demo map_demo.cpp

← <vector>  |  🏠 Index  |  <algorithm> →