std::map and std::multimap

Ordered key-value pairs

Interview Relevant: Associative containers

Map and Multimap

Key-value pairs stored in sorted order by key.

Code Examples

Ordered key-value containers.

cpp
1#include <map>
2
3// map - unique keys
4map<string, int> ages;
5ages["Alice"] = 25;
6ages["Bob"] = 30;
7ages.insert({"Charlie", 35});
8
9// Access
10int age = ages["Alice"];      // Creates if not exists!
11int age2 = ages.at("Bob");    // Throws if not exists
12
13// Check existence
14if (ages.find("Dave") != ages.end()) { }
15if (ages.count("Alice")) { }
16
17// Iterate (sorted by key)
18for (const auto& [name, age] : ages) {
19    cout << name << ": " << age << endl;
20}
21
22// multimap - duplicate keys allowed
23multimap<string, int> scores;
24scores.insert({"Alice", 90});
25scores.insert({"Alice", 85});
26
27auto range = scores.equal_range("Alice");
28for (auto it = range.first; it != range.second; ++it) {
29    cout << it->second << " ";
30}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In